Skip to content

Instantly share code, notes, and snippets.

@bsharathchand
Last active August 29, 2015 14:16
Show Gist options
  • Save bsharathchand/a37d26a47b383c6fcaf1 to your computer and use it in GitHub Desktop.
Save bsharathchand/a37d26a47b383c6fcaf1 to your computer and use it in GitHub Desktop.
Fix for Mockito ClassCastException When running TestSuites in JUnit

##Mockito framework throws ClassCastException when running TestSuites.

Writing TestCases using JUnit and Mockito and running them as testsuites at times throws exceptions.

I faced the issue when

  • There is a TestCase X that creates a stub of Class A and performs some tests
  • There is another TestCase Y; which will use Class A as is.
  • Running TestCase X, TestCase Y independantly then both will execute flawlessly.
  • When TestSuite Z is created by combining TestCase X, TestCase Y then only one TestCase class succeeds(Executed First) and other Fails.

The problem I believe is because Mockito uses a cache of the objects that it mocks, and when objects uses the original objects that casting of MockObjects to RealObjects throw ClassCastException.

Solution to the above problem is to disable the Objenesis Cache of Mockito by overriding the DefaultMockitoConfiguration by creating a class as shown below.

package org.mockito.configuration;

public class MockitoConfiguration extends DefaultMockitoConfiguration {

	@Override
	public boolean enableClassCache() {
		return false;
	}
}

Note: The package and class name should not change

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment