Ignacio Garat
Ignacio Garat

Reputation: 1556

How to test POST method using Mockito

HI have the following test and I cannot make it work:

protected HttpClient mHttpClientMock;
protected HttpPost mHttpPostMock;
protected HttpResponse mHttpResponseMock;
protected StatusLine mStatusLineMock;
protected HttpEntity mHttpEntityMock;
protected ContentResolver mResolver;

    protected void setUp() throws Exception {
    super.setUp();
    // Create mocks.
    mHttpPostMock = Mockito.mock(HttpPost.class);
    mHttpClientMock = Mockito.mock(HttpClient.class);
    mHttpResponseMock = Mockito.mock(HttpResponse.class);
    mStatusLineMock = Mockito.mock(StatusLine.class);
    mHttpEntityMock = Mockito.mock(HttpEntity.class);

    prepareMocks();

    // Obtain Content Resolver.
    mResolver = getContext().getContentResolver();
}


protected void prepareMocks() throws IOException {
    // Create mocked response.
    // Define expected calls.
    Mockito.when(mHttpClientMock.execute(Mockito.isA(HttpPost.class)));
//Mockito.when(mHttpResponseMock.getStatusLine()).thenReturn(mStatusLineMock);
//  Mockito.when(mStatusLineMock.getStatusCode()).thenReturn(HttpStatus.SC_OK);
//  Mockito.when(mHttpResponseMock.getEntity()).thenReturn(mHttpEntityMock);
    Mockito.when(mHttpClientMock.execute(Mockito.mock(Markup.class)));
 //  Mockito.when(mHttpEntityMock.writeTo(Mockito.mock(Markup.class));
}

How do I prepare my (Markup.class) Post, so I can test it later on.

Thank you very much Best Regards.

Upvotes: 2

Views: 18579

Answers (2)

Piotr Kochański
Piotr Kochański

Reputation: 22672

Testing web service with Mockito is doable, but if you want to test dynamic behaviour it is much better to use RestAssured testing framework. It is mostly designed to test REST web services, but can be also used to test "normal" HTTP form posts.

If you mock everything with Mockito, you would test mostly your mocks, not a real behaviour.

Testing with Mockito would mean that you create mock HTTP request and then pass it to some method which consumes that request. The you can create some assertions that would check if method parsed request properly and gave correct outcome.

Upvotes: 0

Ignacio Garat
Ignacio Garat

Reputation: 1556

This was it!!!

        InputStream jsonResponse = createJsonResponse();
    // Define expected calls.
    Mockito.when(mHttpClientMock.execute(Mockito.isA(HttpPost.class))).thenReturn(mHttpResponseMock);
    Mockito.when(mHttpResponseMock.getStatusLine()).thenReturn(mStatusLineMock);
    Mockito.when(mStatusLineMock.getStatusCode()).thenReturn(HttpStatus.SC_OK);
    Mockito.when(mHttpResponseMock.getEntity()).thenReturn(mHttpEntityMock);
    Mockito.when(mHttpEntityMock.getContent()).thenReturn(jsonResponse);

Upvotes: 4

Related Questions