使用PowerMockito测试Unirest

时间:2019-04-04 19:53:49

标签: java unit-testing testing mockito unirest

我想测试一种使用Unirest将获取请求发送到服务器的方法

我已经使用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();

在getRequest中。

预先感谢

1 个答案:

答案 0 :(得分:0)

您快到了,您忘了设置标题了:

    when(Unirest.get("12345")).thenReturn(getRequest);
    when(getRequest.header("accept", "application/json").thenReturn(getRequest)
    when(getRequest.asJson()).thenReturn(httpResponse);
    when(httpResponse.getStatus()).thenReturn(200);