如何使用自定义Spring作用域进行单元测试(SpringJUnit4ClassRunner)

时间:2014-09-17 10:06:23

标签: java spring junit junit4

我正在使用JUnit测试,在我的JUnit测试中使用@Configuration注释的类中定义的Spring配置。测试看起来像这样:

@ContextConfiguration(classes = MyConfiguration.class})
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class SomeIntegrationTest {

    @Autowired
    private MyConfiguration myConfiguration;

    @Test
    public void someTest() throws Exception {
       myConfiguration.myBean();
    }
}

MyConfiguration中,我想使用Spring范围SimpleThreadScope

@Configuration
public class MyConfiguration {

    @Bean
    @Scope("thread")
    public MyBean myBean() {
        return new MyBean();
    }
}

当我运行测试时,范围未注册。我得到了

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: java.lang.IllegalStateException: No Scope registered for scope 'thread'

我知道如何以编程方式注册自定义作用域: context.getBeanFactory().registerScope("thread", new SimpleThreadScope());
我想避免使用XML Spring配置。

有什么办法,如何在单元测试中注册自定义范围?

1 个答案:

答案 0 :(得分:6)

检查此执行侦听器:

public class WebContextTestExecutionListener extends
            AbstractTestExecutionListener {

        @Override
        public void prepareTestInstance(TestContext testContext) throws Exception {

            if (testContext.getApplicationContext() instanceof GenericApplicationContext) {
                GenericApplicationContext context = (GenericApplicationContext) testContext.getApplicationContext();
                ConfigurableListableBeanFactory beanFactory = context
                        .getBeanFactory();
                Scope requestScope = new SimpleThreadScope();
                beanFactory.registerScope("request", requestScope);
                Scope sessionScope = new SimpleThreadScope();
                beanFactory.registerScope("session", sessionScope);
                Scope threadScope= new SimpleThreadScope();
                beanFactory.registerScope("thread", threadScope);
            }
        }
    }

在测试中你可以把这个

    @ContextConfiguration(classes = MyConfiguration.class})
    @RunWith(SpringJUnit4ClassRunner.class)
    @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
    @TestExecutionListeners( { WebContextTestExecutionListener.class})
    public class UserSpringIntegrationTest {

    @Autowired
    private UserBean userBean;

    //All the test methods
    }