Skip to content Skip to sidebar Skip to footer

Classcastexception Exception When Running Robolectric Test With Power Mock On Multiple Files

So I set up the power mock based on the reference guide here. It all seems to run perfectly fine with a single test class. But when executing multiple JUnit tests I am getting the

Solution 1:

I would suggest to disable ClassCache of Mockito as suggested in the exception message . Here is how I disable Mockito ClassCache by adding a MockitoConfiguration class in Android Studio.

  1. Under your unit test directory, src/test/java, create a package directory that is exactly the same as Mockito configuration package, org/mockito/configuration.

  2. So under the full test directory src/test/java/org/mockito/configuration, add a new class named MockitoConfiguration.

  3. Overwrite the enableClassCache() method as following.

    package org.mockito.configuration;
    
        publicclassMockitoConfigurationextendsDefaultMockitoConfiguration {
    
        @OverridepublicbooleanenableClassCache() {
            returnfalse;
        }
    }
    
  4. When you run your Unit test under src/java/test, your MockitoConfiguration should be loaded and Mockito class cache should be disabled.

Hope it helps.

Solution 2:

So I solved this problem by adding

@PowerMockIgnore({ "*.*" }) 
@PrepareForTest({ StaticClass1.class,StaticClass2.class })

That will make Power mock ignore all the classes. For my case PowerMock was classloading the Bus which in my code was actually mocked by Mockito.Once I added the annotations above all the classes in the testsuite worked without any errors.

Post a Comment for "Classcastexception Exception When Running Robolectric Test With Power Mock On Multiple Files"