简体   繁体   中英

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM