Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw exception instead of returning default value

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?

like image 971
Wolfgang Avatar asked Jun 16 '11 07:06

Wolfgang


People also ask

Is throwing an exception the same as returning a value?

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.

Is throwing exception good practice?

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.

Can you throw an exception and return?

Exceptions shouldn't be returned as a return value or parameter instead of being thrown. Don't throw System. Exception, System. SystemException, System.

Can an exception be a return type?

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)


1 Answers

Replace

when( m.a() ).thenReturn( ... );

with

doReturn( ... ).when(m).a();

like image 51
Arno Fiva Avatar answered Oct 18 '22 16:10

Arno Fiva