1

When I mock Configuration I get an exception that I do not get when mocking other classes such as Resources.

Configuration configuration = mock(Configuration.class);

org.mockito.exceptions.base.MockitoException: 
ClassCastException occurred while creating the mockito proxy :
  class to mock : 'android.content.res.Configuration', loaded by classloader : 'org.robolectric.internal.bytecode.InstrumentingClassLoader@57fffcd7'
  created class : 'android.content.res.Configuration$$EnhancerByMockitoWithCGLIB$$78c79839', loaded by classloader : 'org.mockito.internal.creation.util.SearchingClassLoader@e344ad3'
  proxy instance class : null
  instance creation by : ObjenesisInstantiator

You might experience classloading issues, disabling the Objenesis cache *might* help (see MockitoConfiguration)

I'm not super familar with mockitoi, can anyone advise me how I can properly mock the Configuration class?

user3440639
  • 185
  • 2
  • 12

2 Answers2

0

As they said

'disabling the Objenesis cache might help'

You can create override MockitoConfiguration. To do so

Create a package named org.mockito.configuration under your src/test/java Write the MockitoConfiguration class

Class File

package org.mockito.configuration;

public class MockitoConfiguration extends DefaultMockitoConfiguration {

  @Override
  public boolean enableClassCache() {
    return false;
  }
}
Shalu T D
  • 3,921
  • 2
  • 26
  • 37
0

According to this android.content.res.Configuration is a final class.

Mockito normally is unable to mock final classes. You might want to use PowerMockito instead.


Edit:
According to this answer there is an opt-in feature for mockito that I have not between aware of. It might be worth a try.


However since PowerMockito has the same issue, it might be something else completly that prevents it from working.

second
  • 4,069
  • 2
  • 9
  • 24
  • `PowerMockito.mock(Configuration.class);` gives the same error. – user3440639 Aug 16 '19 at 17:17
  • You added the correct class(es) to the `@PrepareForTest` annotation and used the correct `Runner`? If you can add a [mre] using PowerMockito to your question. – second Aug 16 '19 at 17:22
  • Also note that there are some issues with the classloader of `roboelectrics` and the one `powermockito` and/or `mockito` is using, so that really might just be a variant of a known issue. – second Aug 16 '19 at 17:27