具有Retrofit2和Mockito或Robolectric的Android单元测试 [英] 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单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文