I'm new to Mockito and want to use it in unit tests.
What I don't like is mocks created with Mockito.mock(Class<T>)
return default values (like null
) for methods that have no behavior explicitly defined. Instead, I want them to throw an exception in this case so I know that I need to add this definition.
I tried the following:
SomeType m = mock( SomeType.class, new ThrowsException( new SomeRuntimeException( ... ) ) );
when( m.a() ).thenReturn( ... );
m.a(); // ok
m.b(); // throws exception
But that doesn't work because the exception is thrown already during the call to when()
.
Is there some other way to achieve this?
It's not possible to both throw an exception and return a value from a single function call. Perhaps it does something like returning false if there's an error, but throwing an exception if the input is invalid.
The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.
Exceptions shouldn't be returned as a return value or parameter instead of being thrown. Don't throw System. Exception, System. SystemException, System.
If we use exceptions, it's easy. Think of exceptions as a separate return type that gets used only when needed. So we just define all the exceptions and throw them when needed: void f(Number x, Number y)
Replace
when( m.a() ).thenReturn( ... );
with
doReturn( ... ).when(m).a();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With