【问题标题】:Having trouble with a mock object unit test模拟对象单元测试遇到问题
【发布时间】: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。

【问题讨论】:

    标签: java eclipse easymock


    【解决方案1】:

    你的假设是正确的。当您说.andReturn(Instant.from(this.midnight)).times(2) 时,传递给.andReturn 的确切值会重复两次。

    你可以做.andReturn(Instant.from(this.midnight)).andReturn(Instant.from(this.midnight)),这会给你两个瞬间。但作为一般规则,这对于单元测试来说是非常糟糕的形式。 Instant.from(this.midnight) 来自于测试之外,因此无法预测两次调用此函数会导致相同的值还是不同的值,从而使测试具有不确定性。好的集成测试,不适用于单元测试,您将使用模拟。最好使用实数,例如.andReturn(Instant.fromEpochSecond(10)).andReturn(Instant.fromEpochSecond(15))。

    您没有提供有关 st 的大量详细信息,以及您认为测试不应返回 73 而不是 71 的任何原因。

    【讨论】:

    • 感谢您的帮助。这完全解决了我的问题。
    猜你喜欢
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多