我想使用模拟测试restTemplate.getForObject方法,但有问题。我刚接触Mockito,所以我读了一些关于使用Mockito测试restTemplate的博客,但仍然不能写出成功的测试。要测试的类是:
package rest;
@PropertySource("classpath:application.properties")
@Service
public class RestClient {
private String user;
// from application properties
private String password;
private RestTemplate restTemplate;
public Client getClient(final short cd) {
restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(user, password));
Client client = null;
try {
client = restTemplate.getForObject("http://localhost:8080/clients/findClient?cd={cd}",
Client.class, cd);
} catch (RestClientException e) {
println(e);
}
return client;
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
public void setRestTemplate(final RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}我的测试类:
package test;
@PropertySource("classpath:application.properties")
@RunWith(MockitoJUnitRunner.class)
public class BatchRestClientTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private RestClient restClient;
private MockRestServiceServer mockServer;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void getCraProcessTest() {
Client client=new Client();
client.setId((long) 1);
client.setCd((short) 2);
client.setName("aaa");
Mockito
.when(restTemplate.getForObject("http://localhost:8080/clients/findClient?cd={cd},
Client.class, 2))
.thenReturn(client);
Client client2= restClient.getClient((short)2);
assertEquals(client, client2);
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public RestClient getRestClient() {
return restClient;
}
public void setRestClient(RestClient restClient) {
this.restClient = restClient;
}
}它返回null,而不是预期的客户端,Object类的restTemplate工作正常。我只想写一个测试。我是不是遗漏了什么或者做错了测试?感谢您的指导。
发布于 2019-08-15 01:27:15
改用下面的代码:
Mockito.when(restTemplate.getForObject(
"http://localhost:8080/clients/findClient?cd={id}",
Client.class,
new Object[] {(short)2})
).thenReturn(client);第三个参数是varargs。因此,您需要在测试中包装到一个Object[]中,否则Mockito无法匹配它。请注意,这会在您的实现中自动发生。
另外:
在问题中的例子中,你忘记了终止你的url (
")。url:...?cd={cd}而不是...?cd={id}。(正如@ArnaudClaudel之前在comments).
restTemplate.getInterceptors()定义行为所以我预计它会因为一个NullPointerException而失败,
尝试对BasicAuthenticationInterceptor.执行add操作时
此外,您可能希望查看my answer here,了解如何模拟getForObject方法的另一个示例。请注意,它不包括任何实参为null的情况。
https://stackoverflow.com/questions/57496753
复制相似问题