使用Mockito和Retrofit 2.0

时间:2015-11-19 08:37:04

标签: android mockito retrofit rx-java android-testing

我尝试使用Retrofit为我的api通话(通过Mockito 2.0制作)创建单元测试。

这似乎是使用Mockito Retrofit时最受欢迎的博客。

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

不幸的是,它使用早期版本的Retrofit,并且取决于CallbacksRetrofitError,它们已从2.0停止。

如何使用Retrofit 2.0执行此操作?

P.S。:我使用RxJavaretrofit,因此适用于RxJava的内容会非常棒。谢谢!

1 个答案:

答案 0 :(得分:2)

在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()));
    }

另请阅读:Square retrofit server mock for testing

希望有所帮助