Skip to content
Advertisement

Mocking nested retrofit api calls using MockWebServer

I am writing a junit test using okhttp3.mockwebserver for a retrofit2 rest api.

The trimmed down api looks like this:

JavaScript

The api is then injected to another class which delegates the calls thusly:

JavaScript

I do the following in my test:

JavaScript

Because the implementation of cancelOrder() calls api.cancelOrder() and then api.getOrders(), I added two mocked responses corresponding to each. However, looks like only the first mocked responses gets returned. For the second (getOrders), the mock server actually tries to connect over REST and then fails by timing out.

Any ideas as to how to mock responses for nested calls?

Cheers!

Advertisement

Answer

I ended up using the Dispatcher to check the path of the request. If the path ends in “get-orders”, I send mocked response for Orders otherwise for cancel orders.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement