Mocking final class.

If you try to create mock of a final class you will get following error

java.lang.IllegalArgumentException: Cannot subclass final class class com.unittest.FinalClass
	at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
	at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
	at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
	at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
	at net.sf.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
	at org.easymock.internal.ClassProxyFactory.createProxy(ClassProxyFactory.java:181)
	at org.easymock.internal.MocksControl.createMock(MocksControl.java:60)
	at org.powermock.api.easymock.PowerMock.doCreateMock(PowerMock.java:2212)
	at org.powermock.api.easymock.PowerMock.doMock(PowerMock.java:2163)
	at org.powermock.api.easymock.PowerMock.createMock(PowerMock.java:89)
	at com.mycompany.test.UnitTestFinal.testFinalWithMock(UnitTestFinal.java:41)

Final class can be easily mocked using @RunWith and @PrepareForTest.


@RunWith(PowerMockRunner.class)
@PrepareForTest(FinalClass.class)
public class UnitTestFinal {

FinalClass finalClassToBeMocked = createNiceMock(FinalClass.class); //createMock will also work.
		expect(mockedFinalClass.getLength((String)EasyMock.anyObject())).andReturn(new Integer(5));
		replay(mockedFinalClass);
		classUsingFinal.setFinalClass(mockedFinalClass);
		int length = classUsingFinal.doSomeThingWithFinalClass("kumar");
		assertEquals(5, length);

Static Import in eclipse using content assist (CTRL + spacebar (windows))

It took me a while to get content assist on static imports in eclipse. Thought it will useful…

Advertisements