我可以测试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 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!