gpt4 book ai didi

android - 在 Retrofit 2.0 中使用 Mockito

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:59:50 34 4
gpt4 key购买 nike

我正在尝试使用 Mockito 为我的 api 调用(通过 Retrofit 2.0 进行)创建单元测试。

这似乎是关于将 MockitoRetrofit 结合使用的最受欢迎的博客。

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 一起使用的东西会很棒。谢谢!

最佳答案

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

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

在这里你会找到这个 fragment :

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\"," +
" \"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

希望对你有帮助

关于android - 在 Retrofit 2.0 中使用 Mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33798806/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com