I'm new to PowerMock and can't find an example that matches my situation.
It's nothing complicated-- I am trying to use PowerMock+EasyMock to mock a final class in a TestNG test.
Here's the final class:
public final class MyFinalClass {
private String myString = "someString";
public final String getMyString() {
return myString;
}
}
The class under test delegates to an instance of the final class:
public class MyActiveClass {
private MyFinalClass finalClass;
public String getFinalString() {
return finalClass.getMyString();
}
public void setFinalClass(MyFinalClass finalClass) {
this.finalClass = finalClass;
}
}
And here's the Test class:
import static org.easymock.EasyMock.expect;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.Test;
@PrepareForTest({ MyFinalClass.class })
public class MyTestClass extends PowerMockTestCase {
private MyActiveClass activeClass = new MyActiveClass();
private MyFinalClass mockFinalClass;
@Test
public void getFinalString() {
String expectedString = "mockedReturnString";
mockFinalClass = PowerMock.createMock(MyFinalClass.class);
activeClass.setFinalClass(mockFinalClass);
expect(mockFinalClass.getMyString()).andReturn(expectedString);
PowerMock.replayAll();
Assert.assertEquals(activeClass.getFinalString(), expectedString);
PowerMock.verifyAll();
}
}
But when I run the test, I get an illegal argument exception complaining that MyFinalClass is not an interface:
FAILED: getFinalString
java.lang.IllegalArgumentException: MyFinalClass is not an interface
at java.lang.reflect.Proxy.getProxyClass(Unknown Source)
at java.lang.reflect.Proxy.newProxyInstance(Unknown Source)
at org.easymock.internal.JavaProxyFactory.createProxy(JavaProxyFactory.java:24)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:51)
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 MyTestClass.getFinalString(MyTestClass.java:22)
...
What am I missing? Thanks in advance for your help!!!
Here are some options:
MyFinalClass
and mock that interface instead.MyFinalClass
, you could use a wrapper object, which delegates to MyFinalClass
and mock the wrapper object in your test.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With