Mockito Uri.parse always returns null

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.


The problem here is the fact that android.jar file that is used to run unit tests does not contain any actual code. This way android.net.Uri will return null by default and using

android {
  // ...
  testOptions { 
    unitTests.returnDefaultValues = true
  }
}

will not solve the issue for this case, since default return value for method still null

The solution for me was to use the Unmock plugin which sole purpose is to unmock some of the classes/packages from android.jar and give the full implementation for those.

In this specific case, simply add the snippet to you build.gradle file

apply plugin: 'de.mobilej.unmock'
 //...
unMock {
    keepStartingWith "android.net.Uri"
}

I got around this by using the Roboelectric test runner.

@RunWith(RobolectricGradleTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(19))
class WeekPageViewModelConverterTests {
...
}