Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 669
Shane Doyle Avatar asked Mar 29 '14 14:03

Shane Doyle


People also ask

What is mocking API calls?

A mock API server or mock server API imitates a real API server by providing realistic mock API responses to requests. They can be on your local machine or the public Internet. Responses can be static or dynamic, and simulate the data the real API would return, matching the schema with data types, objects, and arrays.

Should you mock API calls?

However, whether your API is still in development, or you are working on new features, testing expected behaviors systematically can save a lot of time and make it easier to identify problems. Developing mock API calls can help you use valuable unit tests, without the problems associated with calling a live API.


1 Answers

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.

like image 159
Shane Doyle Avatar answered Nov 15 '22 08:11

Shane Doyle