[英]How to use custom Spring scope with unit tests (SpringJUnit4ClassRunner)
I am using JUnit tests with Spring configuration defined in a class annotated with @Configuration
in my JUnit Test. 我使用JUnit测试,在与注释的类定义Spring配置
@Configuration
在我的JUnit测试。 The tests looks like this: 测试如下所示:
@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();
}
}
In MyConfiguration
, I would like to use Spring scope SimpleThreadScope
: 在
MyConfiguration
,我想使用Spring作用域SimpleThreadScope
:
@Configuration
public class MyConfiguration {
@Bean
@Scope("thread")
public MyBean myBean() {
return new MyBean();
}
}
When I run the test, the scope is not registered, though. 但是,当我运行测试时,范围未注册。 I get
我懂了
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: java.lang.IllegalStateException: No Scope registered for scope 'thread'
I am aware how a custom scope can be registered programatically: context.getBeanFactory().registerScope("thread", new SimpleThreadScope());
我知道如何以编程方式注册自定义范围:
context.getBeanFactory().registerScope("thread", new SimpleThreadScope());
and I would like to avoid using XML Spring configuration. 而且我想避免使用XML Spring配置。
Is there any way, how can I register the custom scope in the unit test? 有什么办法,如何在单元测试中注册自定义范围?
Check this execution listener: 检查此执行侦听器:
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);
}
}
}
in the test you can put this 在测试中,你可以把这个
@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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.