模拟在测试类中使用的不同类?

时间:2017-09-07 21:10:04

标签: java unit-testing powermock easymock

如何使用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中的其余参数不会被打印,因为它根本就没有被调用过。

我在这里遗漏了什么吗?

1 个答案:

答案 0 :(得分:3)

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