2015-11-19 6 views
7

Я пытаюсь создать модульные тесты для своих вызовов api (сделанных через Retrofit 2.0) с использованием Mockito.Использование Mockito с Retrofit 2.0

Это, казалось, самый популярный блог об использовании Mockito с Retrofit.

http://mdswanson.com/blog/2013/12/16/reliable-android-http-testing-with-retrofit-and-mockito.html

К сожалению, она использует более ранние версии Retrofit, и зависит от Callbacks и RetrofitError, которые прекратили от 2,0.

Как вы это делаете с Retrofit 2.0?

P.S .: Я использую RxJava вместе с retrofit, поэтому что-то, что работает с RxJava, было бы замечательно. Благодаря!

+0

вы смотрели на классах OkHttp в MockWebServer и MockResponse ли? Они могут делать все это без зависимости от Mockito ... –

ответ

0

на официальном хранилище Модернизированный есть пример, который может быть полезным: 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

Надеется, что это поможет