This simple unit test always passes and I can't figure out why.
@RunWith(JUnit4.class) class SampleTest { @Test testSomething() { Uri uri = Uri.parse("myapp://home/payments"); assertTrue(uri == null); } }
What I have tried so far is using a "traditional" URI (http://example.com
) but uri
was also null
.
It is an immutable one-to-one mapping to a resource or data. The method Uri. parse creates a new Uri object from a properly formated String .
I resolve this problem with Robolectric.
these are my unit test config
build.gradle
dependencies { ... testCompile 'junit:junit:4.12' testCompile "org.robolectric:robolectric:3.4.2" }
test class
@RunWith(RobolectricTestRunner.class) public class TestClass { @Test public void testMethod() { Uri uri = Uri.parse("anyString") //then do what you want, just like normal coding } }
kotlin
@RunWith(RobolectricTestRunner::class) class TestClass { @Test fun testFunction() { val uri = Uri.parse("anyString") //then do what you want, just like normal coding } }
it works for me, hope this can help you.
Check if you have the following in your app's gradle file:
android { ... testOptions { unitTests.returnDefaultValues = true }
Uri
is an Android class and as such cannot be used in local unit tests, without the code above you get the following:
java.lang.RuntimeException: Method parse in android.net.Uri not mocked. See http://g.co/androidstudio/not-mocked for details.
The code above suppresses this exception and instead provides dummy implementations returning default values (null
in this case).
The other option is that you are using some framework in your tests that provides implementations of the methods in Android classes.
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