3

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. I'm using the compat library so I cannot inject my code to mock everything. 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? I would like to white list some classes. I mean I know that some classes are easy to mock like Intent or SharedPreferences.

rekire
  • 47,260
  • 30
  • 167
  • 264
  • `@Spy` does exactly this. However I am not sure if this is exactly what you are looking for. Could you provide an example class that you would like to test, and which fields you want to run the concrete implementation for. – Magnilex Sep 30 '15 at 11:02

1 Answers1

2

I found a great library called unmock which exactly does what I need. 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 PendingIntents cannot been used since it required some native implementations however I could mock the relevant parts so I can unit test them anyway.

rekire
  • 47,260
  • 30
  • 167
  • 264