I'm writing an SDK for our MBaaS service. I use Retrofit2 for my REST calls.
I've an Interceptor (very similar to this) for refreshing an expired token that does a pretty complicated if-else cases. For testing the interceptor, I need to mock our API which I do using MockRetrofit library. So far so good! (See end of question for some info on my interceptor class)
Here's the code:
@Before
public void setup() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BacktoryClient.BASE_URL)
.client(new OkHttpClient.Builder().addInterceptor(new RetryWithRefreshedTokenInterceptor()).build())
.build();
NetworkBehavior behavior = NetworkBehavior.create();
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
.networkBehavior(behavior)
.build();
delegate = mockRetrofit.create(AuthApiDefinition.class);
}
@Test
public void testRetryWithRefreshedToken() throws Exception {
SimpleMock apiMock = new SimpleMock(delegate);
Response<SomeApiResponse> response = apiMock.someApiCall(<parameters>).execute();
// assert part
}
The problem is that response object in test method is what it should be (indication that mocking part is OK) but RetryWithRefreshedTokenInterceptor interceptor is not being called. So I assume that MockRetrofit ignores the OkHttpClient.
Now asking the real question, is this some kind of bug or I've completely misunderstood the usage of MockRetrofit library? If it was you, how you were testing the interceptor?
More info on RetryWithRefreshedTokenInterceptor: It checks if the response code is 401 or not and if so calls a method of our SDK which itself calls a method of our API (here from the mocked API) to get a new token and saves that in persistent storage (The amount of logic handled in API methods used in interceptor is big enough I can't isolate the interceptor to test it with MockWebserver)