2015-11-19 10 views
7

私はRetrofit 2.0で作成した私のapi呼び出しの単位テストをMockitoで作成しようとしています。改造した2.0のMockitoの使用

Mockitoを使用すると、これは最も人気のあるブログのようでした。

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

残念ながら、Retrofitの以前のバージョンを使用し、2.0から廃止さCallbacksRetrofitError、に依存します。

どのようにRetrofit 2.0でこれを行いますか?

P .:私はRxJavaretrofitと一緒に使用していますので、RxJavaで動作するものは素晴らしいでしょう。ありがとう!

+0

を助けるホープ?彼らはMockito依存関係なしでこれをすべて行うことができます... –

答えて

0

役立ち例がありますレトロフィットの公式リポジトリに: https://github.com/square/retrofit/tree/master/retrofit-mock

私も見つけた:https://touk.pl/blog/2014/02/26/mock-retrofit-using-dagger-and-mockito/

ここでは、このフラグメント見つけるだろう:

ユニットテストを

アプリの開発中に、いつでもサーバーにリクエストを送信できます(または ) ime)ので、模擬サーバーなしで暮らすことが可能ですが、 が吸うことも可能です。残念ながら、模擬テストなしで良い テストを書くことはできません。下に2つの単体テストがあります。実際には は何もテストしませんが、簡単な方法で模倣する方法を示しますRetrofit サービスMockitoDaggerを使用しています。また

@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クラスを見てきました、それは

関連する問題