Search code examples
androidrobolectricandroid-testing

Mock Api Responses in Android Testing


I'm looking for a way to mock api responses in android tests.

I have read the roboelectric could be used for this but I would really appreciate any advice on this.


Solution

  • After a small bit of looking around on the web I have found MockWebServer to be what I was looking for.

    A scriptable web server for testing HTTP clients. This library makes it easy to test that your app Does The Right Thing when it makes HTTP and HTTPS calls. It lets you specify which responses to return and then verify that requests were made as expected.

    To get setup just add the following to your build.gradle file.

    androidTestCompile 'com.google.mockwebserver:mockwebserver:20130706'
    

    Here is a simple example taking from their GitHub page.

    public void test() throws Exception {
        // Create a MockWebServer. These are lean enough that you can create a new
        // instance for every unit test.
        MockWebServer server = new MockWebServer();
    
        // Schedule some responses.
        server.enqueue(new MockResponse().setBody("hello, world!"));
    
        // Start the server.
        server.play();
    
        // Ask the server for its URL. You'll need this to make HTTP requests.
        URL baseUrl = server.getUrl("/v1/chat/");
    
        // Exercise your application code, which should make those HTTP requests.
        // Responses are returned in the same order that they are enqueued.
        Chat chat = new Chat(baseUrl);
    
        chat.loadMore();
        assertEquals("hello, world!", chat.messages());
    
        // Shut down the server. Instances cannot be reused.
        server.shutdown();
      }
    

    Hope this helps.