【问题标题】:Unit testing using the real implementation (classes)使用真实实现(类)进行单元测试
【发布时间】:2015-12-25 09:46:34
【问题描述】:

我想知道是否有办法避免嘲笑某些课程。我正在研究与通知相关的更大的单元测试。我遇到了多个我能够解决的问题。

现在我被 PendingIntentNotification.Builder 甚至可能是 Notification 这样的类所困。我正在使用 compat 库,因此我无法注入代码来模拟所有内容。我仍然不知道如何模拟构建器模式。

您能否给我一个参考,如何避免 Android Studio 注入每次调用都返回 null 的虚拟对象?我想将一些课程列入白名单。我的意思是我知道有些类很容易模拟,例如 IntentSharedPreferences

【问题讨论】:

  • @Spy 正是这样做的。但是,我不确定这是否正是您要寻找的。您能否提供一个您想要测试的示例类,以及您想要为其运行具体实现的字段。

标签: android unit-testing mockito powermock powermockito


【解决方案1】:

我找到了一个很棒的库,名为 unmock,它正是我所需要的。这是我的测试所需的示例配置:

unMock {
    // URI to download the android-all.jar from. e.g. https://oss.sonatype.org/content/groups/public/org/robolectric/android-all/
    downloadFrom 'https://oss.sonatype.org/content/groups/public/org/robolectric/android-all/4.3_r2-robolectric-0/android-all-4.3_r2-robolectric-0.jar'

    keep 'android.os.Bundle'
    keepStartingWith 'android.content.Intent'
    keepStartingWith 'android.content.ComponentName'
    keep 'android.app.Notification'
    keepStartingWith 'android.app.Notification$'
    keep 'android.net.Uri'
    keepStartingWith 'android.widget.RemoteViews'
    keep 'android.util.SparseIntArray'
    keep 'android.util.SparseArray'
    keep 'com.android.internal.util.ArrayUtils'
    keep 'com.android.internal.util.GrowingArrayUtils'
    keep 'libcore.util.EmptyArray'

    keepStartingWith "libcore."
    keepStartingWith "com.android.internal.R"
    keepStartingWith "com.android.internal.util."
    keepAndRename "java.nio.charset.Charsets" to "xjava.nio.charset.Charsets"
}

PendingIntents 无法使用,因为它需要一些本机实现,但是我可以模拟相关部分,以便无论如何都可以对它们进行单元测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 2019-03-07
    • 2020-02-05
    • 1970-01-01
    • 2011-08-23
    • 2014-11-19
    相关资源
    最近更新 更多