Search code examples
androidunit-testingtestingmocking

Mockito Uri.parse always returns null


I have this production method:

public boolean onShouldOverrideUrlLoading(String url) {
    boolean isConsumed = false;
    if (url.contains("code=")) {
         Uri uri = Uri.parse(url);
         String authCode = uri.getQueryParameter("code");
         mView.authCodeObtained(authCode);
         isConsumed = true;
    }
    return isConsumed;
}

And I have this Mockito test method:

@Test
public void onShouldOverrideUrlLoadingOnAuthCodeObtained(){

    String code = "someCode";

    boolean isConsumed = mPresenter.onShouldOverrideUrlLoading("http://localhost/?code=" + code);

    verify(mView, times(1)).authCodeObtained(code);
    assertEquals(isConsumed, true);
}

But it seems once the code runs and it reaches Uri.parse(url), I get a null pointer. What am I missing? In production this works perfectly. Only when testing, Uri.parse() returns null.

Thank you!


Solution

  • The problem probably lies in Uri class, as the code being tested is static code (Uri.parse(...)), Uri is probably badly initializing in the test environment. Note there's two uri classes in the Android SDK :

    I'm not an Android developer, but you may want to check the test environment.