Uri.parse()总是在单元测试中返回null

3k-*_*3k- 19 android unit-testing uri

这个简单的单元测试总是通过,我无法弄清楚原因.

@RunWith(JUnit4.class)
class SampleTest {
    @Test testSomething() {
        Uri uri = Uri.parse("myapp://home/payments");
        assertTrue(uri == null);
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止我所尝试的是使用"传统"URI(http://example.com),但uri也是null.

Jef*_* Ma 18

我用Robolectric解决了这个问题.

这些是我的单元测试配置

的build.gradle

dependencies {
...
testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.4.2"
}
Run Code Online (Sandbox Code Playgroud)

考试班

@RunWith(RobolectricTestRunner.class)
public class TestClass {

    @Test
    public void testMethod() {
      Uri uri = Uri.parse("anyString")
      //then do what you want, just like normal coding
    }
}
Run Code Online (Sandbox Code Playgroud)

它适合我,希望这可以帮助你.

  • 在“kotlin”的最新版本中,您必须使用“@RunWith(RobolectricTestRunner::class)” (4认同)
  • 为什么这个-1?在我看来,这是真正正确的答案,因为Robolectric为您提供了Uri的实际实现,而不仅仅是模拟,以及您需要对Android进行单元测试所需的所有其他实现. (3认同)

Mar*_*nak 12

检查您的应用程序的gradle文件中是否包含以下内容:

android {
    ...
    testOptions {
        unitTests.returnDefaultValues = true
    }
Run Code Online (Sandbox Code Playgroud)

Uri 是一个Android类,因此无法在本地单元测试中使用,如果没有上面的代码,您将获得以下代码:

java.lang.RuntimeException: Method parse in android.net.Uri not mocked. See http://g.co/androidstudio/not-mocked for details.
Run Code Online (Sandbox Code Playgroud)

上面的代码抑制了这个异常,而是提供了返回默认值的虚拟实现(null在本例中).

另一个选择是您在测试中使用了一些框架,它提供了Android类中方法的实现.

  • 我已经添加了,但仍然无法正常工作 (3认同)

Raf*_*zki 5

Uri 是 Android 类,因此在用于测试之前需要对其进行模拟。

例如,请参阅此答案:https : //stackoverflow.com/a/34152256/5199320