15

I have a data-driven Android app scaffold. Adding tests, aiming for 100% coverage. Using OkHttp.

How do I transparently intercept calls to my server with mock responses?

Want this for—end-to-end as well as—unit tests. E.g.: setting build-type to MockServer should load an app that will show mock responses in the emulator.

A T
  • 13,008
  • 21
  • 97
  • 158
  • Hmm, [mock-server](http://www.mock-server.com) might be what I'm looking for. – A T Oct 14 '16 at 05:47
  • The closest I found was [`angular/in-memory-web-api`](https://github.com/angular/in-memory-web-api) in the web world (TypeScript/JavaScript, Angular 2). Its examples are lacking, would be good to know if it supports full CRUD across HTTP verbs. – A T Oct 24 '16 at 09:27

2 Answers2

1

Did you look into okhttp mockwebserver?

I use it for mocking responses and verifying/showing requests.

If you want to use this with a build type, you can generate an Android resource or java constant in gradle and then start the server and set the path accordingly.

Ole
  • 480
  • 4
  • 11
  • Thanks but that doesn't seem to go far enough. It's only useful for unit testing, not for e2e and live-app [without backend] testing. – A T Oct 24 '16 at 09:28
0

For a unit tests, you should be able to write your code in such a way as to isolate the usage of OkHttp. In doing this, you can mock out the client (using something like Mockito) and have it behave however you want. After all, in a unit test we only want to test a single piece of code, not any of it's dependencies.

Something like this in Java. Likewise, the pattern works elsewhere (like Javascript)

public class ClassUnderTest {

    private final OkHttpClient client;

    public ClassUnderTest(OkHttpClient client) {
        this.client = client;
    }
    // Other code...
}

// In your tests
OkHttpClient mockClient = mock(OkHttpClient.class);
when(mockClient.newCall(any(Request.class)).thenThrow(...);
ClassUnderTest testClass = new ClassUnderTest(mockClient);

verify(mockClient).doSomething();

For integration tests, mockwebserver looks to be your best bet (as others have mentioned).

Howard Grimberg
  • 2,128
  • 2
  • 16
  • 28
  • Thanks but that doesn't seem to go far enough. It's only useful for unit testing, not for e2e and live-app [without backend] testing. – A T Oct 24 '16 at 09:28