0

I have this code that I want to test:

public List<Map<String, Object>> getMaps (Query query) throws CustomException {
   Response<MapsResponse> response = mapsApi.get(); // this is a retrofit2 response
   if (!response.isSuccessful()) {
      handle(response); // throws CustomException
   }
   .
   .
   .
}

So I mocked it with mockito, but when I try to do:

retrofit2.Response<MapsResponse> response = retrofit2.Response.error(500, ResponseBody.create(null, content))
when(mapsApi.get()).thenReturn(response);

It says it cannot resolve method 'thenReturn...'

Does anyone know how can I mock an error response (error HTTP code) that will trigger my exception? Thanks!

Dan798
  • 19
  • 4
  • Check your imports. Seems like you've imported the wrong `when`. – Matt Jan 01 '22 at 15:14
  • Can someone please post a working example? (Mocking a retrofit2 response) I think I'll manage to fix it from there. – Dan798 Jan 01 '22 at 15:27

1 Answers1

0

I usually use Mockito like this

Import Retrofit Mock

<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>retrofit-mock</artifactId>
    <version>${version.retrofit}</version>
    <scope>test</scope>
</dependency>

Create and use the mock

import retrofit2.mock.Calls;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;

...

Api api = mock(Api.class); // Mockito mock

...

when(api.doSomething(param)).thenReturn(Calls.response(response));

Retrofit Mock is used only to generate the response.

I found this answer, I hope this helps you