Android Unit Test with Retrofit2 and Mockito or Robolectric(使用 Retrofit2 和 Mockito 或 Robolectric 进行 Android 单元测试)
问题描述
我可以测试retrofit2beta4 的真实反应吗?我需要 Mockito 还是 Robolectic?
Can I test real response from retrofit2beta4? Do i need Mockito or Robolectic?
我的项目中没有活动,它将是一个库,我需要测试服务器是否正确响应.现在我有这样的代码并卡住了......
I don't have activities in my project, it will be a library and I need to test is server responding correctly. Now I have such code and stuck...
@Mock
ApiManager apiManager;
@Captor
private ArgumentCaptor<ApiCallback<Void>> cb;
@Before
public void setUp() throws Exception {
apiManager = ApiManager.getInstance();
MockitoAnnotations.initMocks(this);
}
@Test
public void test_login() {
Mockito.verify(apiManager)
.loginUser(Mockito.eq(login), Mockito.eq(pass), cb.capture());
// cb.getValue();
// assertEquals(cb.getValue().isError(), false);
}
我可以做出虚假的回应,但我需要测试真实的.是成功吗?身材对吗?你能帮我写代码吗?
I can make fake response, but I need to test real. Is it success? Is it's body correct? Can you help me with code?
推荐答案
答案比我想象的要简单:
The answer is too easy than i expected:
使用 CountDownLatch 让您的测试等到您调用 countDown()
Using CountDownLatch makes your test wait until you call countDown()
public class SimpleRetrofitTest {
private static final String login = "your@login";
private static final String pass = "pass";
private final CountDownLatch latch = new CountDownLatch(1);
private ApiManager apiManager;
private OAuthToken oAuthToken;
@Before
public void beforeTest() {
apiManager = ApiManager.getInstance();
}
@Test
public void test_login() throws InterruptedException {
Assert.assertNotNull(apiManager);
apiManager.loginUser(login, pass, new ApiCallback<OAuthToken>() {
@Override
public void onSuccess(OAuthToken token) {
oAuthToken = token;
latch.countDown();
}
@Override
public void onFailure(@ResultCode.Code int errorCode, String errorMessage) {
latch.countDown();
}
});
latch.await();
Assert.assertNotNull(oAuthToken);
}
@After
public void afterTest() {
oAuthToken = null;
}}
这篇关于使用 Retrofit2 和 Mockito 或 Robolectric 进行 Android 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Retrofit2 和 Mockito 或 Robolectric 进行 Android 单


基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01