我有一个我想测试的 Spring 组件,这个组件有一个 autowired 属性,我需要更改它以进行单元测试。问题是,该类在构造后方法中使用了自动装配组件,因此我无法在实际使用之前替换它(即通过 ReflectionTestUtils)。
我该怎么做?
这是我要测试的课程:
@Component
public final class TestedClass{
@Autowired
private Resource resource;
@PostConstruct
private void init(){
//I need this to return different result
resource.getSomething();
}
}
这是测试用例的基础:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= "classpath:applicationContext.xml")
public class TestedClassTest{
@Autowired
private TestedClass instance;
@Before
private void setUp(){
//this doesn't work because it's executed after the bean is instantiated
ReflectionTestUtils.setField(instance, "resource", new Resource("something"));
}
}
在调用 postconstruct 方法之前,有没有办法用其他东西替换资源?想告诉 Spring JUnit runner 自动装配不同的实例吗?
原文由 NeplatnyUdaj 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以提供一个新的 testContext.xml,其中您定义的
@Autowired
bean 是您测试所需的类型。