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.
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.
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.
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.
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.
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