作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有一个我想测试的 Spring 组件,并且这个组件有一个 Autowiring 的属性,我需要更改它以进行单元测试。问题是,该类在 post-construct 方法中使用 Autowiring 组件,因此在实际使用之前我无法替换它(即通过 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 Autowiring 不同的实例?
最佳答案
您可以使用 Mockito .我不确定 PostConstruct
的具体情况,但这通常有效:
// Create a mock of Resource to change its behaviour for testing
@Mock
private Resource resource;
// Testing instance, mocked `resource` should be injected here
@InjectMocks
@Resource
private TestedClass testedClass;
@Before
public void setUp() throws Exception {
// Initialize mocks created above
MockitoAnnotations.initMocks(this);
// Change behaviour of `resource`
when(resource.getSomething()).thenReturn("Foo");
}
关于java - Spring JUnit : How to Mock autowired component in autowired component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299513/
我是一名优秀的程序员,十分优秀!