如何仅使用 powerMock 或 EasyMock 来模拟在另一个类中使用的类,我只能使用这两个框架,我知道我们可以使用 Mockito,但由于我们的代码库仅包含 easymock 和 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 testing\n");
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
代码流程并没有超出expect(class2.getVoidCall()).andReturn(20).atLeastOnce();
并且 getRecord 中的其余语句不会打印,因为它根本没有被调用。
我在这里遗漏了什么吗?
最佳答案
SecondClass#getVoidCall()
方法 (public static int getVoidCall() {...}
) 是一个 static
方法,并且,因此, mock 有点不同。
替换前两行:
@Test
public void testMock() throws Exception {
SecondClass class2 = createMock(SecondClass.class);
expect(class2.getVoidCall()).andReturn(20).atLeastOnce();
使用以下几行(并准备类(class)):
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
关于java - 模拟被测试类中使用的不同类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46105139/