【发布时间】:2019-12-21 03:10:48
【问题描述】:
我想使用模拟测试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 工作正常。我只想写测试。我是否遗漏了什么或以错误的方式进行测试?
感谢您的指导。
【问题讨论】:
-
您的意思是“它正在返回 null”而不是“它不是返回 null”吗?
-
是的。更新 。谢谢
-
您使用了两个不同的网址,一个以
..?cd={cd}结尾,另一个以...?cd={id}结尾。尝试使用相同的 -
已更新。谢谢 。还是一样的问题