模拟在被测 class 中使用的不同 class?

Mock a Different class which is used in the class under test?

我如何仅使用 powerMock 或 EasyMock 模拟另一个 class 中使用的 class,我只能使用这两个框架,我知道我们可以使用 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 方法,因此,模拟有点不同。

替换前两行:

@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