【问题标题】:Mockito java - test method call with different argumentsMockito java - 使用不同参数的测试方法调用
【发布时间】:2016-11-30 10:31:57
【问题描述】:

我正在尝试测试这个方法,看看是否在没有参数的情况下调用了 searchProfile:

public void searchProfile(Long searchTerm) {
    this.searchTerm = searchTerm;
    searchProfile();
}

public void searchProfile() {
     //...
}

这是我的测试用例,我用一个参数调用方法,并期望调用没有参数的方法

@Test
public void testSearchProfile() throws Exception {
    CustomerProfileController sutStub = Mockito.mock(CustomerProfileController.class);

    doNothing().when(sutStub).searchProfile();

    sutStub.searchProfile(0L);

    verify(sutStub, times(1)).searchProfile();
}

我怎样才能做到这一点?现在它只是给我一个错误:

比较失败:

预期:customerProfileController.searchProfile();

实际:customerProfileController.searchProfile(0);

【问题讨论】:

  • 我想接受的答案是正确的,因为它可以解决您的问题。但是你为什么要测试一个模拟?测试CustomerProfileController 的具体实例并模拟其依赖关系不是更好吗,模拟测试通常采用的方式?
  • @Magnilex 你是对的,我想监视这些方法。经过一些研究,我已经一起更改了测试实现。谢谢!
  • 是的,我正要添加一个答案,说间谍可能是更好的选择,但这个问题没有足够的背景让我这样做。

标签: java junit mockito junit4


【解决方案1】:

你应该使用

Mockito.when(sutStub.searchProfile(Mockito.anyLong())).thenCallRealMethod();

在准备模拟时。

【讨论】:

  • 太棒了!这给了我构建解决方案的先机。它应该是 doCallRealMethod().when(sutStub).searchProfile(Mockito.anyLong()); 而不是因为 void 方法。谢谢你:)
  • 对,没注意到它是无效的。
  • 也许使用间谍也是一种选择
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
相关资源
最近更新 更多