我想测试一个使用 Unirest 向服务器发送 get 请求的方法
我已经使用PowerMockito和Mockito来测试一些方法,但是当我尝试在下面的方法上执行此操作时,我得到空指针异常。
这是我想要测试的方法:
public HttpResponse<JsonNode> jsonRequest(String path) {
HttpResponse<JsonNode> jsonResponse = null;
try {
jsonResponse = Unirest
.get(path)
.header("accept", "application/json")
.asJson();
} catch (UnirestException e) {
System.out.println("Server is unreachable at the moment. Please try again later");
}
return jsonResponse;
}
这是测试用例:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Unirest.class)
public class TestModel {
@Mock
private GetRequest getRequest;
@Mock
private HttpResponse<JsonNode> httpResponse;
@InjectMocks
DatabaseModel databaseModel;
@Test
public void testController() {
PowerMockito.mockStatic(Unirest.class);
JsonNode jsonNode = mock(JsonNode.class);
when(Unirest.get("12345")).thenReturn(getRequest);
when(getRequest.asJson()).thenReturn(httpResponse);
when(httpResponse.getStatus()).thenReturn(200);
assertEquals(200, databaseModel.jsonRequest("12345").getStatus());
}
所以我期望得到 200(或我将决定的任何状态\身体(但是由于某种原因,我得到了java.lang.NullPointerException。它将我引导到这一行:
.asJson();
在获取请求中。
提前致谢
你快到了,你忘了设置标题:
when(Unirest.get("12345")).thenReturn(getRequest);
when(getRequest.header("accept", "application/json").thenReturn(getRequest)
when(getRequest.asJson()).thenReturn(httpResponse);
when(httpResponse.getStatus()).thenReturn(200);