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

Mif*_*eet 2 java junit spring junit4

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

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

MyConfiguration,我想使用Spring范围SimpleThreadScope:

@Configuration
public class MyConfiguration {

    @Bean
    @Scope("thread")
    public MyBean myBean() {
        return new MyBean();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行测试时,范围没有注册.我明白了

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: java.lang.IllegalStateException: No Scope registered for scope 'thread'
Run Code Online (Sandbox Code Playgroud)

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

有什么办法,我怎样才能在单元测试中注册自定义范围?

Xst*_*ian 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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在测试中你可以把它

    @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
    }
Run Code Online (Sandbox Code Playgroud)