模拟方法不抛出异常

mas*_*y88 3 java exception mocking mockito

我有在特殊情况下抛出异常的方法。我想编写一个测试用例来检查未抛出异常时的行为。我在文档或示例中找不到这个。请帮忙。

例如:

when(validator.validate(any(ValidationData.class))).thenThrow(new ValidationException());
Run Code Online (Sandbox Code Playgroud)

但我想测试一下是否根本没有抛出异常:

class Validator {
    void validate(ValidationData dataToValidate) throws Exception {
    }
}
Run Code Online (Sandbox Code Playgroud)

例如我需要类似的东西:

when(doSomething()).thenNotThrowException
Run Code Online (Sandbox Code Playgroud)

或者

when(doSomething()).thenDoNothing
Run Code Online (Sandbox Code Playgroud)

sta*_*032 6

默认情况下,Mockito的mock对void方法不做任何事情,所以你不需要写任何东西。

如果你想明确地执行此操作,请尝试以下操作:

doNothing().when( validator ).validate( any() );