gpt4 book ai didi

java - 如何在单元测试中使用自定义 Spring 作用域 (SpringJUnit4ClassRunner)

转载 作者:行者123 更新时间:2023-12-04 02:28:13 30 4
gpt4 key购买 nike

我在 JUnit 测试中使用带有 @Configuration 注释的类中定义的 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();
}
}

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 配置。

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

最佳答案

检查这个执行监听器:

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
}

关于java - 如何在单元测试中使用自定义 Spring 作用域 (SpringJUnit4ClassRunner),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887688/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com