在春季测试中请求范围好的豆子适用于 Spring 3.2 或更高版本的解决方案3.2之前春季与听众的解决方案3.2 之前的 Spring 解决方案,带自定义示波器源码

2022-09-01 10:12:33

我想在我的应用中使用请求范围的Bean。我使用JUnit4进行测试。如果我尝试在这样的测试中创建一个:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/TestScopedBeans-context.xml" })
public class TestScopedBeans {
    protected final static Logger logger = Logger
            .getLogger(TestScopedBeans.class);

    @Resource
    private Object tObj;

    @Test
    public void testBean() {
        logger.debug(tObj);
    }

    @Test
    public void testBean2() {
        logger.debug(tObj);
    }

具有以下豆定义:

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean class="java.lang.Object" id="tObj" scope="request" />
 </beans>           

我得到:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gov.nasa.arc.cx.sor.query.TestScopedBeans': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: No Scope registered for scope 'request'
<...SNIP...>
Caused by: java.lang.IllegalStateException: No Scope registered for scope 'request'

所以我发现这个博客似乎很有帮助:http://www.javathinking.com/2009/06/no-scope-registered-for-scope-request_5.html

但我注意到他使用了 AbstractDependencyInjectionSpringContextTests,这似乎在 Spring 3.0 中被弃用了。我现在使用Spring 2.5,但我认为按照文档的建议将此方法切换到使用AbstractJUnit4SpringContextTests应该不会太难(好的,文档链接到3.8版本,但我使用的是4.4)。所以我改变了测试来扩展抽象JUnit4SpringContextTests...相同的消息。同样的问题。现在,我想要重写的 prepareTestInstance() 方法尚未定义。好吧,也许我会把那些 registerScope 调用放到别的地方...因此,我阅读了更多关于TestExecutionListeners的信息,并认为这样会更好,因为我不想继承弹簧包结构。所以我把我的测试改成了:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/TestScopedBeans-context.xml" })
@TestExecutionListeners({})
public class TestScopedBeans {

期望我必须创建一个自定义侦听器,但是当我运行它时。它的工作原理!很好,但为什么呢?我没有看到任何股票侦听器在哪里注册请求范围或会话范围,为什么会这样做?没有什么可说的,我想要的,这可能不是对春季MVC代码的测试......


答案 1

适用于 Spring 3.2 或更高版本的解决方案

从版本 3.2 开始的 Spring 为集成测试提供了对会话/请求范围的 Bean 的支持

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@WebAppConfiguration
public class SampleTest {

    @Autowired WebApplicationContext wac;

    @Autowired MockHttpServletRequest request;

    @Autowired MockHttpSession session;    

    @Autowired MySessionBean mySessionBean;

    @Autowired MyRequestBean myRequestBean;

    @Test
    public void requestScope() throws Exception {
        assertThat(myRequestBean)
           .isSameAs(request.getAttribute("myRequestBean"));
        assertThat(myRequestBean)
           .isSameAs(wac.getBean("myRequestBean", MyRequestBean.class));
    }

    @Test
    public void sessionScope() throws Exception {
        assertThat(mySessionBean)
           .isSameAs(session.getAttribute("mySessionBean"));
        assertThat(mySessionBean)
           .isSameAs(wac.getBean("mySessionBean", MySessionBean.class));
    }
}

阅读更多:请求和会话范围的 Bean


3.2之前春季与听众的解决方案

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@TestExecutionListeners({WebContextTestExecutionListener.class,
        DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class})
public class SampleTest {
    ...
}

WebContextTestExecutionListener.java

public  class WebContextTestExecutionListener extends AbstractTestExecutionListener {
    @Override
    public void prepareTestInstance(TestContext testContext) {
        if (testContext.getApplicationContext() instanceof GenericApplicationContext) {
            GenericApplicationContext context = (GenericApplicationContext) testContext.getApplicationContext();
            ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
            beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST,
                    new SimpleThreadScope());
            beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION,
                    new SimpleThreadScope());
        }
    }
}

3.2 之前的 Spring 解决方案,带自定义示波器

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class, locations = "test-config.xml")
public class SampleTest {

...

}

TestConfig.java

@Configuration
@ComponentScan(...)
public class TestConfig {

    @Bean
    public CustomScopeConfigurer customScopeConfigurer(){
        CustomScopeConfigurer scopeConfigurer = new CustomScopeConfigurer();

        HashMap<String, Object> scopes = new HashMap<String, Object>();
        scopes.put(WebApplicationContext.SCOPE_REQUEST,
                new SimpleThreadScope());
        scopes.put(WebApplicationContext.SCOPE_SESSION,
                new SimpleThreadScope());
        scopeConfigurer.setScopes(scopes);

        return scopeConfigurer

}

或使用 xml 配置

test-config.xml

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="request">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
        <map>
            <entry key="session">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>

源码

所有提供的解决方案的源代码:


答案 2

我已经尝试了几种解决方案,包括使用“WebContextTestExecutionListener”@Marius的解决方案,但它对我不起作用,因为此代码在创建请求范围之前加载了应用程序上下文。

最终帮助我的答案不是新的,但它很好:http://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/

我只是将以下代码段添加到我的(测试)应用程序上下文中:

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="request">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>

祝你好运!


推荐