【发布时间】:2017-11-08 11:03:54
【问题描述】:
我有三种方法,
- 无效保存(字符串 a,字符串 b)
- String getId(String a, Pojo p)
- 无效更新(字符串 a,字符串 b,字符串实体 c)
这里是实现(不是完整的实现),
String getId(String accessToken, Pojo p) {
//Note that the pojo is for formatting the payload for the request, nothing more
HttpResponse response = httpRequestService.makeGetRequest(url, TOKEN_PREFIX, accessToken,
CONTENT_TYPE);
if (response.getStatusLine().getStatusCode() == 200) {
log.debug("Success");
}
//Code for getting the id from the response
return id;
}
void update(String accassToken, String id, StringEntity payload) {
HttpResponse response = httpRequestService.makePutRequest(url + id,
TOKEN_PREFIX, accessToken, CONTENT_TYPE, payload);
if (response.getStatusLine().getStatusCode() == 200) {
log.debug("Success");
}
}
void save(String accessToken, String payload) {
//The getId() is called here
String id = getId(/*arguments*/);
if(id == null) {
log.error("Error");
} else {
//The update() is called here
update(/*arguments*/);
}
}
如前所述,getId 和 update 方法在 save 方法中调用,getId 和 update 方法都有 HTTP 调用。
我必须为 save() 方法编写一个单元测试。这是我尝试过的。
//This is an interface with methods to call HTTP requests.
HttpRequestService httpRequestService = Mockito.mock(HttpRequestService.class);
//Constructor injection
ClassWithMethods a = new ClasswithMethods(httpRequestService);
HttpResponse responseGet = Mockito.mock(HttpResponse.class);
StatusLine statusLineGet = Mockito.mock(StatusLine.class);
HttpEntity httpEntity = Mockito.mock(HttpEntity.class);
Mockito.when(responseGet.getStatusLine()).thenReturn(statusLineGet);
Mockito.when(statusLineGet.getStatusCode()).thenReturn(200);
Mockito.when(responseGet.getEntity()).thenReturn(httpEntity);
Mockito.when(httpEntity.getContent()).thenReturn(IOUtils.toInputStream(stream));
Mockito.when(httpRequestService.makeGetRequest(url, TOKEN_PREFIX, accessToken,
CONTENT_TYPE).thenReturn(responseGet);
HttpResponse responsePut = Mockito.mock(HttpResponse.class);
StatusLine statusLinePut = Mockito.mock(StatusLine.class);
Mockito.when(responsePut.getStatusLine()).thenReturn(statusLinePut);
Mockito.when(statusLinePut.getStatusCode()).thenReturn(200);
Mockito.when(httpRequestService.makePutRequest(url + id, TOKEN_PREFIX,
accessToken, CONTENT_TYPE, payloadEntity).thenReturn(responsePut);
a.save(accessToken, payload);
但是在测试时,responsePut 返回一个空值。参数也匹配。
问题:如何测试这个调用两个HTTP方法的save方法?
这可能不是最好的方法。如果有更好的方法来测试这样的方法,请提出建议。
谢谢
请注意,httpRequestService 是一个带有 HTTP 调用方法的接口,也使用了构造函数注入。
【问题讨论】:
-
"但是在测试的时候,responsePut 返回了一个空值。" 一个变量没有返回任何东西。请在实际行为中更加明确,并显示失败测试消息。
-
@davidxxx,它只是在 update() 方法中的
if (response.getStatusLine().getStatusCode() == 200)行抛出 NullPointerException。当我调试它时,它显示 responsePut 为空。 -
识别错误行对于理解或猜测原因很重要。我做了一个回答。
标签: java unit-testing junit mocking mockito