【问题标题】:How to stop method calling a method in another class in Mockito?如何停止方法调用 Mockito 中另一个类中的方法?
【发布时间】:2016-08-19 09:56:34
【问题描述】:

我有以下方法在我的Java 服务类中进行测试:

public void findPersonToDelete(String id){

    //repository method then called
   personRepository.findPersonAndDelete(id);


}

问题在于 personRepository 调用了其他代码,该代码抛出了Null Pointer

我尝试使用以下行来阻止 personRepository 调用其他方法:

  Mockito.doNothing().when(personRepository).findPersonAndDelete(id);

但是错误仍然存​​在?我该如何解决这个问题?

【问题讨论】:

  • 如果你没有用id的任何值调用它,它将正常执行该方法。
  • personRepository 是模拟的吗?
  • 尝试anyInt() 而不是特定值。另外PersonRepository 需要是mockspy
  • @Heisenberg 是的,它是一个模拟

标签: java unit-testing nullpointerexception mockito method-call


【解决方案1】:

如果您的 PersonRepository 有一个设置器,您可以模拟该类并将其设置在您的服务中,这样模拟的类将被调用,您只能检查它是否被调用。 就像这样:

PersonRepository repo = Mockito.mock(PersonRepository.class);
service.setPersonRepository(repo);
service.findPersonToDelte(1);

然后检查您要测试的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    相关资源
    最近更新 更多