Uri.parse () always returns null in unit test

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); } } 

I tried to use the "traditional" URI ( http://example.com ), but the uri also null .

+6
source share
4 answers

Check if there is a gradle file in your application:

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

Uri is an Android class and, as such, cannot be used in local block 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 that return default values ​​( null in this case).

Another option is that you use some framework in your tests, which provides the implementation of methods in Android classes.

+6
source

Uri is an Android class, so you need to mock it before using it in tests.

See this answer for example: fooobar.com/questions/992628 / ...

+2
source

I solve this problem with Robolectric .

this is 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 } } 

It works for me, hope this can help you.

+2
source

Finally, I just changed my code to accept the URI as String , so now it works in both production and test, and omits the use of Uri.parse() . Now that I need a URI, I just use uri.toString() instead of parsing String .

0
source

Source: https://habr.com/ru/post/1012406/


All Articles