I want to test a method that sends a get request to a server using Unirest
I have used PowerMockito and Mockito to test some methods, but when I try to do it on the method below, I get null pointer exception.
This is the method I want to test:
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;
}
And this is the test case:
@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());
}
So I expect to get 200 (Or any status\body I will decide on) But for some reason I get java.lang.NullPointerException which directs me to this line:
.asJson();
in the getRequest.
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire