我试图使用 Power Mock 模拟某些场景。
我在以下测试方法上收到断言错误 - returnSevenTest()
。
待测类
package tutorial.one;
public class TutorialOne {
//fields
private int number;
private String name;
private final DependentFinalClass finalObj;
public TutorialOne (DependentFinalClass dep) {
this.finalObj= dep ;
}
public TutorialOne(int number, String name) {
super();
this.number = number;
this.name = name;
finalObj = new DependentFinalClass();
}
public static int returnTwo()
{
return 2;
}
public int returnThree()
{
return (returnTwo()+1);
}
public final int returnFour()
{
return (returnThree()+1);
}
private final int returnFive(int addOne)
{
return (returnFour()+addOne);
}
public int returnSix(int addOne)
{
return (returnFive(1)+addOne);
}
public int returnSeven()
{
final int addValue= finalObj.callMeToAddOne(true);
return (returnSix(1)+ addValue);
}
}
最后一堂课
package tutorial.one;
public final class DependentFinalClass {
final int callMeToAddOne(Boolean need)
{
if(need.equals(true))
return 1;
else
return 1;
}
}
使用 Power Mock+ Easy Mock 测试表演类
package tutorial.one;
import stmts ....
@RunWith(PowerMockRunner.class)
//We prepare the IdGenerator for test because the static method is normally not
//mockable
@PrepareForTest({TutorialOne.class, DependentFinalClass.class}) public class TutorialOneTests {
@Test
public void returnSevenTest() throws Exception
{
int expected=7;
TutorialOne privateTest =createPartialMock(TutorialOne.class,"returnFive" );
DependentFinalClass finalDependentTest = createPartialMock(DependentFinalClass.class,"callMeToAddOne" );
expect(finalDependentTest.callMeToAddOne(true)).andReturn(1);
expectNew(TutorialOne.class, finalDependentTest).andReturn(privateTest);
expectPrivate(privateTest, "returnFive", 1).andReturn(5);
replayAll(TutorialOne.class,finalDependentTest,privateTest);
int actual = privateTest.returnSeven();
verifyAll();
assertEquals("Expected and actual did not match", expected, actual);
resetAll();
}
}
收到错误:
java.lang.AssertionError:
Expectation failure on verify:
tutorial.one.TutorialOne(tutorial.one.DependentFinalClass$$EnhancerByCGLIB$$fa2e41a0@5a9de6): expected: 1, actual: 0
at org.powermock.api.easymock.internal.invocationcontrol.NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(NewInvocationControlAssertionError.java:20)
at org.powermock.api.easymock.PowerMock.verifyClass(PowerMock.java:2279)
at org.powermock.api.easymock.PowerMock.verify(PowerMock.java:1646)
at org.powermock.api.easymock.PowerMock.verifyAll(PowerMock.java:1586)
at tutorial.one.TutorialOneTests.returnSevenTest(TutorialOneTests.java:174)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
任何帮助都非常感谢!谢谢