我有一个遗留代码,其中包含我想要测试的以下方法。如果我删除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。
- 填充真实的
DemographicsForm
,以便它们与比较器一起工作。在你的情况下,getter似乎太复杂了,所以它不起作用 - 部分模拟
DemographicsForm
,从而模拟烦人的getter - 将比较器移动到字段以注入
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-->
}
这样你就可以很容易地模仿比较器。