Mockito 不再验证交互,但省略 getter

发布于 2024-09-03 00:50:26 字数 319 浏览 4 评论 0原文

Mockito api 提供了方法:

Mockito.verifyNoMoreInteractions(someMock);

但是在 Mockito 中是否可以声明我不希望与给定的模拟进行更多交互,但与其 getter 方法交互除外?

在一个简单的场景中,我测试 SUT 仅更改给定模拟的某些属性,而保留其他属性未开发。

在示例中,我想测试 UserActivationService 是否更改 User 类实例上的 Active 属性,但不对 Role、Password、AccountBalance 等属性执行任何操作。

Mockito api provides method:

Mockito.verifyNoMoreInteractions(someMock);

but is it possible in Mockito to declare that I don't want more interactions with a given mock with the exceptions of interactions with its getter methods?

The simple scenario is the one in which I test that the SUT changes only certain properties of a given mock and leaves other properties untapped.

In example I want to test that UserActivationService changes property Active on an instance of class User but does't do anything to properties like Role, Password, AccountBalance, etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

各自安好 2024-09-10 00:50:26

不,Mockito 目前没有此功能。如果您经常需要它,您可以使用反射魔法自己创建它,尽管这会有点痛苦。

我的建议是使用 VerificationMode 验证您不想频繁调用的方法的交互次数:

@Test
public void worldLeaderShouldNotDestroyWorldWhenMakingThreats() {
  new WorldLeader(nuke).makeThreats();

  //prevent leaving nuke in armed state
  verify(nuke, times(2)).flipArmSwitch();
  assertThat(nuke.isDisarmed(), is(true));
  //prevent total annihilation
  verify(nuke, never()).destroyWorld();
}

当然,WorldLeader API 设计的敏感性可能值得商榷,但作为示例,它应该做。

No this functionality is not currently in Mockito. If you need it often you can create it yourself using reflection wizzardry although that's going to be a bit painful.

My suggestion would be to verify the number of interactions on the methods you don't want called too often using VerificationMode:

@Test
public void worldLeaderShouldNotDestroyWorldWhenMakingThreats() {
  new WorldLeader(nuke).makeThreats();

  //prevent leaving nuke in armed state
  verify(nuke, times(2)).flipArmSwitch();
  assertThat(nuke.isDisarmed(), is(true));
  //prevent total annihilation
  verify(nuke, never()).destroyWorld();
}

Of course the sensibility of the WorldLeader API design might be debatable, but as an example it should do.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文