当方法调用实际返回某些内容时,有没有办法让 Mockito doNothing()

joh*_*doe 5 java junit mockito

因此,我有这个方法在内部调用另一个服务,出于测试目的,我不关心这个内部调用,也不希望这个内部服务执行任何操作。

例如

public void testMyMethod() {
        List<String> strings = otherService.getList(Employee);
}
Run Code Online (Sandbox Code Playgroud)

现在我想以这种 otherService.getList(Employee) 不执行任何操作的方式使用mockito。它只是跳过此操作的执行。

And*_*aya 2

如果您已经注入模拟 otherService,则所有方法调用都otherService.getList(Employee.class)将默认返回空值,除非您明确告诉 Mockito仅当它们不是 void 方法时才List返回某些内容(通过使用)。返回什么thenReturn取决于方法中的业务流程。getList

TLDR,明确告诉 Mockito 对方法中的所有方法调用要做什么getList,以便返回值符合您的期望。