Android Unit Test with Retrofit2 and Mockito or Robolectric



Answers

The answer is too easy than i expected:

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;
}}
Question

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?




MockWebServer throwing java.lang.reflect.InvocationTargetException

Ah figured it out. It was Robolectric:

changed:

@Config(constants = BuildConfig.class, sdk = JELLYBEAN, packageName = "com.test.mc.instagram")

TO

@Config(constants = BuildConfig.class, sdk = 23, packageName = "com.test.mc.instagram")

see this: https://github.com/square/okhttp/issues/2591




Related



Tags