na oficjalnym repozytorium Retrofit jest przykładem, który może być przydatny: https://github.com/square/retrofit/tree/master/retrofit-mock
Ja również znaleźć: https://touk.pl/blog/2014/02/26/mock-retrofit-using-dagger-and-mockito/
Tutaj można znaleźć ten fragment:
Jednostka Testy
Podczas tworzenia aplikacji możesz wysyłać żądania do serwera przez cały czas (lub większość t ime), więc można żyć bez wyśmiewanego serwera, to jest do bani, ale jest możliwe. Niestety nie jesteś w stanie napisać dobrych testów bez makiety. Poniżej znajdują się dwa testy jednostkowe. W rzeczywistości one nie testują niczego, ale w prosty sposób pokazują, jak kpić z usługi Retrofit
przy użyciu Mockito
i 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()));
}
Czytaj także: Square retrofit server mock for testing
Mam nadzieję, że pomoże
Pan spojrzał na zajęciach MockWebServer i MockResponse OkHttp za? Mogą to zrobić bez zależności Mockito ... –