Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Mock throw an exception, then return a value?

I am using JUnit 4 and Mockito 2. I am trying to mock a situation where the mocked function returns an exception the first time it is called, and on the subsequent call a valid value is returned. I tried simply having a thenThrow() followed by a thenReturn(), but that is not the correct method apparently

when(stmt.executeUpdate()).thenThrow(new SQLException("I have failed."));
when(stmt.executeUpdate()).thenReturn(1);
sut.updateValue("1");
verify(dbc).rollback();
sut.updateValue("2");
verify(dbc).commit();

Both calls, however, result in a call to rollback(), which is in the catch statement.

like image 216
Wige Avatar asked Aug 09 '17 17:08

Wige


People also ask

Can we set values on mock objects?

You can set the mock object property to the value returned by the mock object method. To achieve this, specify separate behaviors for the method and the property. You can specify one behavior at a time. For more information about mock object behavior, see Specify Mock Object Behavior.

How do you throw an exception in JUnit Mockito for void method?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.

What happens if a test method throws an exception?

If you write a test method that throws an exception by itself or by the method being tested, the JUnit runner will declare that this test fails.


1 Answers

the easiest way is this:

when(stmt.executeUpdate())
     .thenThrow(new SQLException("I have failed."))
     .thenReturn(1);

But a single method in a unit test should verify a single expectation about the codes behavior. Therefore the better way is to writ two separate test methods.

like image 158
Timothy Truckle Avatar answered Sep 30 '22 16:09

Timothy Truckle