我是 PowerMock 的新手,找不到符合我情况的示例。
这并不复杂——我正在尝试使用 PowerMock+EasyMock 来模拟 TestNG 测试中的最终类。
这是最后一堂课:
public final class MyFinalClass {
private String myString = "someString";
public final String getMyString() {
return myString;
}
}
被测类委托给最终类的一个实例:
public class MyActiveClass {
private MyFinalClass finalClass;
public String getFinalString() {
return finalClass.getMyString();
}
public void setFinalClass(MyFinalClass finalClass) {
this.finalClass = finalClass;
}
}
这是测试类:
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();
}
}
但是当我运行测试时,我得到一个非法参数异常,抱怨 MyFinalClass 不是接口:
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)
...
我错过了什么?在此先感谢您的帮助!!!