Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What I have tried so far is using a "traditional" URI (http://example.com) but uri was also null.

like image 511
3k- Avatar asked Nov 17 '16 11:11

3k-


People also ask

What is the functionality of Uri parse ()?

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 .


2 Answers

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.

like image 54
Jeffery Ma Avatar answered Oct 01 '22 22:10

Jeffery Ma


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.

like image 38
Marcin Jedynak Avatar answered Oct 01 '22 23:10

Marcin Jedynak