16

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.

0

3 Answers 3

13

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.

1
  • 3
    In case anyone is wondering, the reason you may want something like this is if the method you are testing is calling the mocked method multiple times. Then you need something like this to control execution.
    – gagarwa
    Sep 5, 2020 at 10:59
8

use thenAnswer() with a custom Answer with some state, something like:

class CustomAnswer extends Answer<Integer> {

    private boolean first = true;

    @Override
    public Integer answer(InvocationOnMock invocation) {
        if (first) {
            first = false;
            throw new SQLException("I have failed.");
        }
        return 1;
    }
}

Some reading: https://akcasoy.wordpress.com/2015/04/09/the-power-of-thenanswer/ (NB: not my blog)

0
-1

You could make two separate tests. To verify the exception you could do something like:

@Test(expected = SQLException.class)
public void yourTest()throws Exception{
stmt.executeUpdate(); //set your logic to produce the exception
}

Then make another test for the success scenario

1
  • 1
    that's not what was asked - the mocked method needs to fail on first invocation, then return a value
    – ashley
    Oct 10, 2020 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.