android mockito retrofit2,android – 使用Mockito和Retrofit 2.0

该博客展示了如何在Android应用开发中使用Mockito和Dagger来为Retrofit服务编写单元测试。通过创建Mock响应并检查服务方法的预期行为,测试能够独立于实际服务器运行,确保代码质量。
摘要由CSDN通过智能技术生成

在Retrofit的官方存储库中有一个有用的例子:

https://github.com/square/retrofit/tree/master/retrofit-mock

在这里你会发现这个片段:

Unit Tests

During develop of app,you can send requests the server all time(or

most of time) so it is possible to live without mocked server,it

sucks but is possible. Unfortunately you are not able to write good

tests without the mock. Below there are two unit tests. Actually they

do not test anything but in simple way shows how to mock Retrofit

service using Mockito and 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\","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()));

}

希望它有所帮助

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值