包含对包含静态和非静态方法 Java 的最终类的调用的模拟和测试方法

问题描述

我有一个代码,其中包含我要测试的以下方法。如果我删除 Collections.sort 行,则测试用例将正常工作。但我正在尝试用它执行测试用例。

void update(){
   <!-- Other logic-->
      Collections.sort(demographicsForms,DemographicsFormComparator.getInstance()); 
   <!-- Other logic-->
}

demographicsForms一个 Pojo 类,包含基本的 setter 和 getter

DemographicsFormComparator 包含以下代码

public final class DemographicsFormComparator implements Comparator<DemographicsForm> {

    public int compare(DemographicsForm demo1,DemographicsForm demo2) {
        return demo1.getType().getCdfMeaning().compareto(demo2.getType().getCdfMeaning());
    }

    private static DemographicsFormComparator INSTANCE = null;

    public synchronized static DemographicsFormComparator getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new DemographicsFormComparator();
        }
        return INSTANCE;
    }
}

到目前为止我已经尝试过这个

    @Mock
    private DemographicsForm df1;
    @Mock
    private DemographicsForm df2;
    
    @Test
    public void test() {
        final DemographicsFormComparator mockA = PowerMock.createMock(DemographicsFormComparator.class);
        EasyMock.expect(mockA.compare(df1,df2)).andReturn(1).anyTimes();
        PowerMock.mockStatic(DemographicsFormComparator.class);
        EasyMock.expect(DemographicsFormComparator.getInstance()).andReturn(mockA).anyTimes();
        PowerMock.replayAll(mockA);
    }

但上述方法给了我以下错误

java.lang.AssertionError: 
  Unexpected method call DemographicsFormComparator.compare

编辑1: 尝试为人口统计表格传递真实物体

    DemographicsForm df1 = new DemographicsForm();
        DemographicsForm df2 = new DemographicsForm();

        final DemographicsFormComparator mockA = PowerMock.createMock(DemographicsFormComparator.class);
        EasyMock.expect(mockA.compare(df1,df2)).andReturn(1).anyTimes();

        PowerMock.mockStatic(DemographicsFormComparator.class);
        EasyMock.expect(DemographicsFormComparator.getInstance()).andReturn(mockA).anyTimes();

        PowerMock.replayAll();

仍然收到对 compare 的意外呼叫

解决方法

你有多种可能性。它们都不涉及 PowerMock。

  1. 填充实数 DemographicsForm 以便它们与比较器一起使用。在您的情况下,吸气剂似乎太复杂了,所以它不起作用
  2. 部分模拟 DemographicsForm 以便模拟烦人的 getter
  3. 将比较器移动到一个字段以注入它

public class MyClass {
     private final Comparator<DemographicsForm> comparator;
     public MyClass(Comparator<DemographicsForm> comparator) {
        this.comparator = comparator;
     }
     public MyClass() {
        this(DemographicsFormComparator.getInstance());
     }
     void update() {
         <!-- Other logic-->
         Collections.sort(demographicsForms,comparator); 
         <!-- Other logic-->
     }

这样您就可以轻松模拟比较器。