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!
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.
I got around this by using the Roboelectric test runner.
@RunWith(RobolectricGradleTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(19))
class WeekPageViewModelConverterTests {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With