android 在单元测试中,uri.parse()总是返回null

r8uurelv  于 2022-11-20  发布在  Android
关注(0)|答案(6)|浏览(193)

这个简单的单元测试总是通过,我不知道为什么。

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

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

8iwquhpp

8iwquhpp1#

我用Robolectric解决了这个问题。
这些是我单元测试配置
build.gradle

dependencies {
...
testImplementation 'junit:junit:4.12'
testImplementation "org.robolectric:robolectric:3.4.2"
}

测试类

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

对我很有效,希望这能对你有帮助。

l0oc07j2

l0oc07j22#

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

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

Uri是一个Android类,因此不能用于本地单元测试,如果没有上面的代码,您将获得以下内容:

java.lang.RuntimeException: Method parse in android.net.Uri not mocked. See http://g.co/androidstudio/not-mocked for details.

上面的代码抑制了此异常,而是提供了返回默认值的伪实现(在本例中为null)。
另一种选择是在测试中使用一些框架,这些框架提供Android类中方法的实现。

kgsdhlau

kgsdhlau3#

URI是Android类,因此在测试中使用之前需要对其进行模拟。
请参见以下答案示例:https://stackoverflow.com/a/34152256/5199320

7cwmlq89

7cwmlq894#

这是愚蠢的...但我忘了注解我的测试类:@RunWith(AndroidJUnit4::class)
一旦我这样做了,一切都像预期的那样工作。

w8f9ii69

w8f9ii695#

最后,我修改了代码,接受String形式的URI,所以现在它在生产和测试中都可以工作,并且省略了Uri.parse()的使用。现在,在需要URI的地方,我只使用uri.toString(),而不是解析String

wsxa1bj1

wsxa1bj16#

下面的代码解决了我的问题。

@RunWith(AndroidJUnit4::class)
@Config(sdk = [Build.VERSION_CODES.P])
class TestClass

相关问题