Mock and Test方法,该方法包含对包含静态和非静态方法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,以便它们与比较器一起工作。在你的情况下,getter似乎太复杂了,所以它不起作用
  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-->
}

这样你就可以很容易地模仿比较器。

最新更新