模拟对象没有更新值

Mock object did not update value

我正在设置这样的 int 值:

when(status.getCurrentSeq()).thenReturn(0);

当测试用例运行时,代码逻辑将 CurrentSeq 的值设置为 1。

status.setCurrentSeq(1)

但是 currentSeq 在模拟对象中仍然是 0。再次获得 status.getCurrentSeq() 总是 return 0.

您不能在模拟对象上设置值。它仍将 return 被模拟为 return。在这种情况下 0.

如果您不想将方法模拟为 return 0,为什么还要将其模拟为 return 0? 也许完全删除 when(status.getCurrentSeq()).thenReturn(0); 可以解决您的问题。

编辑: 也许您需要打断连续通话?

when(status.getCurrentSeq())
  .thenReturn(0)
  .thenReturn(1);

也可以这样简写:

when(status.getCurrentSeq())
  .thenReturn(0,1);

可以通过以下方式验证此行为:

assertEquals(0, status.getCurrentSeq());
assertEquals(1, status.getCurrentSeq());
assertEquals(1, status.getCurrentSeq());

它会 return 第一次调用模拟方法时为 0,每次连续调用时为 1。