How to mock services with Retrofit 2.0 and the new MockRetrofit class?

clemp6r picture clemp6r · Jan 12, 2016 · Viewed 13.2k times · Source

Using Retrofit 1 we used to mock web services and simulate network latency as following:

MockRestAdapter mockRestAdapter = MockRestAdapter.from(restAdapter);
return mockRestAdapter.create(MyService.class, new MyServiceMock());

Where MyService is the service Interface (returning responses as Rx Observables), and MyServiceMock is a class that implements this interface.

In Retrofit 2.0.0-beta3 there is a brand new mocking system (see: https://github.com/square/retrofit/pull/1343) that is not yet documented. When trying to to something similar I get:

MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).build();
BehaviorDelegate<AuthService> delegate = mockRetrofit.create(MyService.class);

How do I forward calls to MyServiceMock?

Answer

Praveer Gupta picture Praveer Gupta · Jan 12, 2016

Suppose the interface definition is as below:

public interface MyService {
    @GET("/name")
    rx.Observable<String> name();
}

Calls will be forwarded to MyServiceMock using BehaviorDelegate. The BehaviorDelegate applies NetworkBehavior to the responses created by the mock. Note that the mock implementation below takes the BehaviorDelegate as a constructor argument and uses it to return the response.

public class MyServiceMock implements MyService {
    private final BehaviorDelegate<MyService> delegate;

    public MyServiceMock(BehaviorDelegate<MyService> delegate) {
        this.delegate = delegate;
    }

    public Observable<String> name() {
        return delegate.returningResponse("test").name();
    }
}

A sample of a test using the mock service is as shown below:

public class MyServiceTest {

    private final NetworkBehavior behavior = NetworkBehavior.create();
    private final rx.observers.TestSubscriber<String> testSubscriber = TestSubscriber.create();
    private MyService mockService;

    @Before
    public void setUp() throws Exception {
        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl("http://example.com").build();

        MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
                .networkBehavior(behavior).build();

        final BehaviorDelegate<MyService> delegate = mockRetrofit.create(MyService.class);

        mockService = new MyServiceMock(delegate);
    }

    @Test
    public void testSuccessResponse() throws Exception {
        givenNetworkFailurePercentIs(0);

        mockService.name().subscribe(testSubscriber);

        testSubscriber.assertValue("test");
        testSubscriber.assertCompleted();
    }

    @Test
    public void testFailureResponse() throws Exception {
        givenNetworkFailurePercentIs(100);

        mockService.name().subscribe(testSubscriber);

        testSubscriber.assertNoValues();
        testSubscriber.assertError(IOException.class);
    }

    private void givenNetworkFailurePercentIs(int failurePercent) {
        behavior.setDelay(0, MILLISECONDS);
        behavior.setVariancePercent(0);
        behavior.setFailurePercent(failurePercent);
    }
}