本文介紹了使用 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 單元測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!