Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock method to do not throw an exception

I have method that throws an exception in special circumstances. I would like to write a test case that will check behaviour when exception is not thrown. I cannot find this in docs or examples. Please help.

E.g.:

when(validator.validate(any(ValidationData.class))).thenThrow(new ValidationException());

But I would like to test that exception is not thrown at all:

class Validator {
    void validate(ValidationData dataToValidate) throws Exception {
    }
}

e.g. I need something like:

when(doSomething()).thenNotThrowException

or

when(doSomething()).thenDoNothing
like image 692
masterdany88 Avatar asked Sep 17 '25 16:09

masterdany88


1 Answers

By default, Mockito's mock does nothing for void methods, so you don't need to write anything.

If you want to do this explicitly try this:

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

like image 95
staszko032 Avatar answered Sep 19 '25 07:09

staszko032