Uri.parse() always returns null in unit test

不打扰是莪最后的温柔 提交于 2019-12-22 01:34:19

问题


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.


回答1:


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.




回答2:


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

it works for me, hope this can help you.




回答3:


Uri is Android class therefore it needs to be mocked before using in tests.

See this answer for example: https://stackoverflow.com/a/34152256/5199320




回答4:


Finally I just changed my code to accept URIs as String, so now it works both in production and test and omit the usage of Uri.parse(). Now where an URI is needed I just use uri.toString() instead of parsing a String.



来源:https://stackoverflow.com/questions/40653625/uri-parse-always-returns-null-in-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!