[英]How do I mock a locally created object?
这是我的班级。
class Test {
public void print(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.getForObject("url", String.class);
}
}
为了测试这个类,我想模拟“RestTemplate”。 有没有办法在不更改代码的情况下执行此操作。
如果不改变代码就无法做到这一点,至少不是以优雅的方式。
每次输入print()
方法时都会创建一个RestTemplate
的新实例,因此无法传入模拟。
稍微更改方法以使用RestTemplate作为参数。 在运行时,这将是RestTemplate的实际实例,但是当单元测试该方法时,它能够接受模拟。
class Test {
public void print(RestTemplate restTemplate){
restTemplate.getForObject("url", String.class);
}
}
class TestTest {
private final Test instance = new Test();
@Test
public testPrint() {
RestTemplate restTemplateMock = mock(RestTemplate.class);
instance.print(restTemplateMock);
// TODO: verify method calls on the mock
}
}
您希望为测试使用RestTemplate
的注入实例。
@Autowired
private TestRestTemplate restTemplate;
在测试设置中,您可以根据需要模拟restTemplate
的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.