使用Mockito和Retrofit 2.0

A.B*_*.B. 8 android mockito android-testing rx-java retrofit

我正在尝试使用我的api调用(通过Retrofit2.0制作)创建单元测试Mockito.

这似乎是在使用最流行的博客MockitoRetrofit.

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

不幸的是,它使用的是早期版本Retrofit,并且取决于CallbacksRetrofitError,它们从2.0中断.

你是怎么做到的Retrofit 2.0

PS:我使用的是RxJava一起retrofit,让一些有工作RxJava将是巨大的.谢谢!

pio*_*543 3

在 Retrofit 的官方存储库上有一个有用的示例: https: //github.com/square/retrofit/tree/master/retrofit-mock

我还发现:https://touk.pl/blog/2014/02/26/mock-retrofit-using-dagger-and-mockito/

在这里你会找到这个片段:

单元测试

在应用程序的开发过程中,您可以一直(或大部分时间)向服务器发送请求,因此可以在没有模拟服务器的情况下生存,这很糟糕,但也是可能的。不幸的是,如果没有模拟,你就无法编写好的测试。下面有两个单元测试。实际上他们没有测试任何东西,只是以简单的方式展示了如何使用和 来模拟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()));
    }
Run Code Online (Sandbox Code Playgroud)

另请阅读:用于测试的 Square 改造服务器模拟

希望有帮助