简体   繁体   English

使用实际实现(类)进行单元测试

[英]Unit testing using the real implementation (classes)

I'm wondering if there is a way to avoid mocking some classes.我想知道是否有办法避免嘲笑某些类。 I'm working on a bigger unit testing thing related with notifications.我正在研究与通知相关的更大的单元测试。 I run into multiple issues which I was able to fix mostly.我遇到了多个我能够解决的问题。

Now I'm stuck with some classes like PendingIntent , Notification.Builder and probably even Notification .现在我被一些类困住了,比如PendingIntentNotification.Builder甚至可能是Notification I'm using the compat library so I cannot inject my code to mock everything.我正在使用 compat 库,所以我无法注入我的代码来模拟所有内容。 I still have no idea how to mock a builder pattern.我仍然不知道如何模拟构建器模式。

Could you give me a reference how I can avoid that Android Studio injects the dummy objects which return null on every call?你能给我一个参考,我可以如何避免 Android Studio 注入在每次调用时返回 null 的虚拟对象? I would like to white list some classes.我想将一些课程列入白名单。 I mean I know that some classes are easy to mock like Intent or SharedPreferences .我的意思是我知道有些类很容易模拟,例如IntentSharedPreferences

I found a great library called unmock which exactly does what I need.我找到了一个很棒的库,叫做unmock ,它完全符合我的需要。 Here is my example configuration which I need for my tests:这是我的测试所需的示例配置:

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

The PendingIntent s cannot been used since it required some native implementations however I could mock the relevant parts so I can unit test them anyway.无法使用PendingIntent因为它需要一些本机实现,但是我可以模拟相关部分,因此无论如何我都可以对它们进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM