futurice / android-best-practices

Do's and Don'ts for Android development, by Futurice developers
Other
20.35k stars 3.37k forks source link

Use RESTMock for mocking Retrofit REST services #116

Open bryant1410 opened 8 years ago

bryant1410 commented 8 years ago

Regarding #114, we have been using RESTMock to mock Retrofit calls and it's working like a charm! It uses OkHttp's MockWebServer and it allows to define mock responses for matchers. For instance:

RESTMockServer.whenGET(pathContains("users/defunkt"))
            .thenReturnFile(200, "users/defunkt.json");

It also permits to verify if the calls have been done.

djodjoni commented 8 years ago

interesting however there is WireMock : https://github.com/tomakehurst/wiremock, Which can do exactly this and bit more i think :

stubFor(get(urlEqualTo("/my/resource"))
            .withHeader("Accept", equalTo("text/xml"))
            .willReturn(aResponse()
                .withStatus(200)
                .withHeader("Content-Type", "text/xml")
                .withBody("<response>Some content</response>")));

    Result result = myHttpServiceCallingObject.doSomething();

    assertTrue(result.wasSuccessFul());

    verify(postRequestedFor(urlMatching("/my/resource/[a-z0-9]+"))
            .withRequestBody(matching(".*<message>1234</message>.*"))
            .withHeader("Content-Type", notMatching("application/json")));

MockWebServer is also really cool and I use it allot but its power is in full and sequential control of the requests/responses

peter-tackage commented 7 years ago

I've used Wiremock recently and found it be a decent tool. Although, I was using it a way that more resembled blackbox testing; arguably a special case (at least it seemed that way to me). I think that generally, people should see if MockWebServer is adequate for needs before using WireMock.

djodjoni commented 7 years ago

@peter-tackage I agree. MockWebServer with its default dispatcher could be enough for most for the cases and makes you think more about the way/sequence you make network requests which may help in discovering some unexpected side effects.