我在 Spring 中有以下场景:
public class ClassA{
@Autowired
private ClassB classB;
}
我在我的测试类中使用(更准确地说是 Autowiring )ClassA
。但是我想做的是只为我的 Junit 修改 ClassB
,所以当 ClassA
在我的测试类中 Autowiring 时,它会加载修改后的 ClassB
(而不是原来的)。
有办法实现吗?
最佳答案
如果没有 Bean 配置,想不出另一种方法来做到这一点。 您可以通过两种方式进行配置:
首先:
@Configuration
public class AppConfig {
@Bean
public ClassB classB() {
return new ClassB() {
// this is a subclass that inherits everything from ClassB, so override what you want here
}
}
}
第二个:(取自 here)
@RunWith(SpringRunner.class)
@SpringBootTest
public class SomeTest {
// do this if you only want the modified classB in 1 place
@Configuration
static class TestConfig {
@Bean
public ClassB classB () {
return new ClassB() {
// same as the first
}
}
}
@Test
public void testMethod() {
// test
}
}
最后,您可以在主文件夹中创建一个新接口(interface) ClassB
和 ClassBImpl
,在测试文件夹中创建一个新接口(interface) ClassBTestImpl
。您仍然需要使用其中一种配置。
关于java - Spring:在 Junit 中加载的类中 Autowiring 不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46923461/