【发布时间】:2015-10-07 03:10:07
【问题描述】:
我正在玩弄模拟对象,但在设置检查列表是否正确排序的单元测试时遇到了麻烦。这样做的自负是我在嘲笑一个时钟,但仅仅使用 times() 方法是行不通的。该列表应该按升序排列,但获取第一个索引只会返回最后设置的任何值。
作为参考,这是一个有效的模拟测试,用于测试设置在午夜的时钟:
@Test
public void shouldSetAtMidnight() {
expect(mock.instant()).andReturn(Instant.from(this.midnight));
expect(mock.getZone()).andReturn(this.timeZone);
replay(mock);
this.st.setDesiredValue(72);
SetPoint[] sched = this.st.getSchedule();
verify(mock);
assertEquals(LocalTime.MIDNIGHT, sched[0].getScheduledTime());
}
在这里,设置所需值的唯一重要之处在于它向数组添加了一个 SetPoint(setDesiredValue 创建一个具有 int 和 LocalTime 的 SetPoint)。这是我遇到困难的地方:
@Test
public void shouldOrderTwoSetPointsAddedOutOfOrder() {
expect(mock.instant()).andReturn(Instant.from(this.midnight)).times(2);
expect(mock.getZone()).andReturn(this.timeZone).times(2);
replay(mock);
this.st.setDesiredValue(73);
this.st.setDesiredValue(71);
SetPoint[] schedule = this.st.getSchedule();
verify(mock);
assertEquals(71, schedule[0].getTemp());
}
setDesiredValue 应该将 int 值与 LocalTime 相关联,在这种情况下应该是午夜。然后它将具有这些特征的 SetPoint 添加到列表中,并调用 Collection 的 sort() 方法将它们从最低到最高排序。现在,我假设我的问题是我将两个值与完全相同的时间关联起来,尽管这两个期望都调用了 times(2),但我最近才开始使用模拟对象,只是不知道他们知道从这里去哪里。运行此测试返回 73 而不是 71。
【问题讨论】: