我如何模拟仅使用PowerMock或EasyMock在其他类中使用的类,我只能使用这两个框架,我知道我们可以使用Mockito和PowerMock库,我必须仅贴上两个框架。
我的代码(我正在使用PowerMock)
public class ClassUnderTest {
public void getRecord() {
System.out.println("1: In getRecord n");
System.out.println("n 3:"+SecondClass.getVoidCall());
System.out.println("n 4: In getRecord over n");
}
}
我想模拟方法secondclass.getVoidCall()。
public class ArpitSecondClass {
public static int getVoidCall() {
System.out.println("n 2: In ArpitSecondClass getVoidCall for kv testingn");
return 10;
}
}
我的单位测试代码是
@RunWith(PowerMockRunner.class)
@PrepareForTest(TestArpit.class)
public class UniteTestClass {
@Test
public void testMock() throws Exception {
SecondClass class2 = createMock(SecondClass.class);
expect(class2.getVoidCall()).andReturn(20).atLeastOnce();
expectLastCall().anyTimes();
ClassUnderTest a=new ClassUnderTest ();
a.getRecord();
replayAll();
PowerMock.verify();
}
}
基本上我希望输出如下
1: In getRecord
2: In ArpitSecondClass getVoidCall for kv testing
3:20 (Note:This should be overriden by the value I supplied in UnitTest)
4: In getRecord over
但是我使用Unitest代码获得的输出是
2: In ArpitSecondClass getVoidCall for kv testing
代码流不超出期望(class2.getVoidCall())。andreturn(20).atleastonce();
getRecord中的其余措施根本没有打印,因为它根本没有被调用。
我在这里错过了什么吗?
SecondClass#getVoidCall()
方法(public static int getVoidCall() {...}
)是static
方法,因此,模拟器有些不同。
替换前两行:
@Test
public void testMock() throws Exception {
SecondClass class2 = createMock(SecondClass.class);
expect(class2.getVoidCall()).andReturn(20).atLeastOnce();
在下面的行中(并准备课程):
import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.mockStatic;
...
@RunWith(PowerMockRunner.class)
@PrepareForTest({TestArpit.class, SecondClass.class}) // added SecondClass.class here
public class UniteTestClass {
@Test
public void testMock() throws Exception {
mockStatic(SecondClass.class); // changed this line
expect(SecondClass.getVoidCall()).andReturn(20).atLeastOnce(); // changed this line