【问题标题】:Mock a Different class which is used in the class under test?模拟在被测类中使用的不同类?
【发布时间】:2017-09-07 21:10:04
【问题描述】:

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

我在这里遗漏了什么吗?

【问题讨论】:

  • 使用静态方法是一种不好的做法,因为它隐藏了类的依赖关系并使您的代码不灵活且难以重用。因此,与其向您投降糟糕的设计并使用 PowerMock,不如从ArpitSecondClass 的方法中删除static 关键字,并将此类的一个实例作为构造函数参数传递给您的测试类。

标签: java unit-testing powermock easymock


【解决方案1】:

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

【讨论】:

  • 轻松工作。非常感谢
猜你喜欢
  • 2023-02-21
  • 2021-10-10
  • 2014-08-17
  • 2023-03-05
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多