на официальном хранилище Модернизированный есть пример, который может быть полезным: https://github.com/square/retrofit/tree/master/retrofit-mock
Я также нашел: https://touk.pl/blog/2014/02/26/mock-retrofit-using-dagger-and-mockito/
Здесь вы найдете этот фрагмент:
Unit Tests
Во время разработки приложения вы можете отправлять запросы серверу все время (или больше всего t ime), так что можно жить без посмеянного сервера, это отстой, но это возможно. К сожалению, вы не можете написать хорошие тесты без макета. Ниже приведены два модульных теста. На самом деле они не испытывают ничего, но простым способом показывают, как насмехаться Retrofit
с использованием Mockito
и Dagger
.
@RunWith(RobolectricTestRunner.class)
public class EchoServiceTest {
@Inject
protected EchoService loginService;
@Inject
protected Client client;
@Before
public void setUp() throws Exception {
Injector.add(new AndroidModule(),
new RestServicesModule(),
new RestServicesMockModule(),
new TestModule());
Injector.inject(this);
}
@Test
public void shouldReturnOfferInAsyncMode() throws IOException {
//given
int expectedQuantity = 765;
String responseContent = "{" +
" \"message\": \"mock message\"," +
" \"quantity\": \"" + expectedQuantity + "\"" +
"}";
mockResponseWithCodeAndContent(200, responseContent);
//when
EchoResponse echoResponse = loginService.getMessageAndQuantity("test", "test");
//then
assertThat(echoResponse.getQuantity()).isEqualTo(expectedQuantity);
}
@Test
public void shouldReturnOfferInAsyncModea() throws IOException {
//given
int expectedQuantity = 2;
String responseContent = "{" +
" \"message\": \"mock message\"," +
" \"quantity\": \"" + expectedQuantity + "\"" +
"}";
mockResponseWithCodeAndContent(200, responseContent);
//when
EchoResponse echoResponse = loginService.getMessageAndQuantity("test", "test");
//then
assertThat(echoResponse.getQuantity()).isEqualTo(expectedQuantity);
}
protected void mockResponseWithCodeAndContent(int httpCode, String content) throws IOException {
Response response = createResponseWithCodeAndJson(httpCode, content);
when(client.execute(Matchers.anyObject())).thenReturn(response);
}
private Response createResponseWithCodeAndJson(int responseCode, String json) {
return new Response(responseCode, "nothing", Collections.EMPTY_LIST, new TypedByteArray("application/json", json.getBytes()));
}
Читайте также: Square retrofit server mock for testing
Надеется, что это поможет
вы смотрели на классах OkHttp в MockWebServer и MockResponse ли? Они могут делать все это без зависимости от Mockito ... –