gpt4 book ai didi

java - 不同的测试方法使用不同的Spring测试上下文配置

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:54 26 4
gpt4 key购买 nike

我们有一个基于 Spring 的 JUnit 测试类,它使用内部测试上下文配置类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ServiceTest.Config.class)
public class ServiceTest {

@Test
public void someTest() {
...

@Configuration
@PropertySource(value = { "classpath:application.properties" })
@ComponentScan({ "..." })
public static class Config {
...

最近向 Service 类引入了新功能,为此应将相关测试添加到 ServiceTest。然而,这些还需要创建一个不同的测试上下文配置类(现有 Config 类的内部结构相当复杂,如果可能的话,将其更改为同时服务于新旧测试似乎非常困难)

有没有办法实现一个测试类中的某些测试方法使用一个配置类而其他方法使用另一个配置类? @ContextConfiguration 似乎仅适用于类级别,因此解决方案可能是为新测试创建另一个测试类,该测试类将利用其自己的上下文配置类;但这意味着同一个服务类被两个不同的测试类覆盖

最佳答案

根据亚伦关于手动构建上下文的建议,我找不到任何好的示例,所以在花了一些时间让它工作之后,我想我会发布一个我使用的代码的简单版本,以防它对其他人有帮助:

class MyTest {

@Autowired
private SomeService service;
@Autowired
private ConfigurableApplicationContext applicationContext;

public void init(Class<?> testClass) throws Exception {
TestContextManager testContextManager = new TestContextManager(testClass);
testContextManager.prepareTestInstance(this);
}

@After
public void tearDown() throws Exception {
applicationContext.close();
}

@Test
public void test1() throws Exception {
init(ConfigATest.class);
service.doSomething();
// assert something
}

@Test
public void test2() throws Exception {
init(ConfigBTest.class);
service.doSomething();
// assert something
}

@ContextConfiguration(classes = {
ConfigATest.ConfigA.class
})
static class ConfigATest {
static class ConfigA {
@Bean
public SomeService someService() {
return new SomeService(new A());
}
}
}

@ContextConfiguration(classes = {
ConfigBTest.ConfigB.class
})
static class ConfigBTest {
static class ConfigB {
@Bean
public SomeService someService() {
return new SomeService(new B());
}
}

}
}

关于java - 不同的测试方法使用不同的Spring测试上下文配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35086806/

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