我是PowerMock的新手,找不到符合我情况的例子. 这并不复杂 – 我正在尝试使用PowerMock EasyMock来模拟TestNG测试中的最终类. 这是最后一堂课: public final class MyFinalClass { private String myString
这并不复杂 – 我正在尝试使用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) ...
我错过了什么?在此先感谢您的帮助!!!
以下是一些选项:>为MyFinalClass引入一个新接口,然后模拟该接口.>如果您没有编辑MyFinalClass的权限,则可以使用包装器对象,该对象委托给MyFinalClass并模拟测试中的包装器对象.>我不知道“powermock easymock testng”是否可以直接模拟最后一堂课,但在我看来,可以通过反思改变最终属性.所以也许有更好的解决方案.