Dianfang Zheng
Dianfang Zheng

Reputation: 31

Mockito in Android error: java.lang.ClassNotFoundException: android.os.Parcelable

The interface is as follows:

interface ILoginView{
    fun userResponseProcessor(user: User?)
}

I mock the interface in my test class:

 @Mock
 private val mMockLoginView:  ILoginView? = null

when run this test, An error occurred

    Underlying exception : java.lang.IllegalArgumentException: Could not create type

        at org.mockito.internal.runners.DefaultInternalRunner$1.withBefores(DefaultInternalRunner.java:38)
        at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
  ...
    Caused by: java.lang.ClassNotFoundException: android.os.Parcelable
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 75 more

How to solve the error?

Upvotes: 2

Views: 1137

Answers (1)

David Rawson
David Rawson

Reputation: 21497

Firstly please use the correct version of Mockito:

androidTestCompile ''org.mockito:mockito-android:2.8.47' 
testCompile 'org.mockito:mockito-android:2.8.47'

Secondly, there are two types of tests for an Android project: Local Unit tests and Instrumented Tests. See the official documentation for more details

Local Unit Tests run on your laptop or desktop in the JVM there. Hence, they do not have access to the native Android classes like Parcelable and if you run a local unit test against a class that uses those methods you will get errors.

At this stage you have two choices, you can run your tests as instrumented tests on a real device or emulator or you can use a framework like Robolectric which allows you to run local unit tests with all of the native classes like Parcelable

Upvotes: 2

Related Questions