问题
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