Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 949
Alon Minski Avatar asked Aug 16 '15 13:08

Alon Minski


2 Answers

Eventually I used PowerMock on top of Mockito to mock the Uri class. Use these dependecies to add it:

'org.powermock:powermock-api-mockito:1.4.12'
'org.powermock:powermock-module-junit4:1.6.2'

Read about it here.

It enables you to mock static methods, private methods, final classes and more. In my test method I used:

PowerMockito.mockStatic(Uri.class);
Uri uri = mock(Uri.class);

PowerMockito.when(Uri.class, "parse", anyString()).thenReturn(uri);

This passed the line in the actual code and returned a Mocked Uri object so the test could move forward. Make sure to add:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Uri.class})

As annotations on top of the test class name.

Using Robolectric to tackle this issue is also a valid technique.

Hope this helps some what.

like image 58
Alon Minski Avatar answered Sep 18 '22 23:09

Alon Minski


I got around this by using the Roboelectric test runner.

@RunWith(RobolectricGradleTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(19))
class WeekPageViewModelConverterTests {
...
}
like image 21
Brice Pollock Avatar answered Sep 21 '22 23:09

Brice Pollock