1

I would like to doNothing 29 times and when 30 time calling happens, then throw ArithmeticException. But i cannot find anything where to set TIMES attribute. This is my imagination:

@Mock
DAOclass dao;

@Test(expected = ArithmeticException.class)
public void AAA() throws SQLException {
    doThrow(ArithmeticException.class).when(dao,times(30)).methodABC();
    for (int i = 0; i < 30; i++) {
        dao.nothing();
    }
}

But of course when(dao,times(30)) is nonsense because i cannot add times(30) as second argument at when block. Does somebody have some idea what could be optional solution of this problem?

Btw. my target is definitely not MANUALLY write 30 times doNothing().doNothing().doNothing.... doThrow(...).when(...)

nyi
  • 3,123
  • 4
  • 22
  • 45
user7968180
  • 145
  • 1
  • 15
  • 1
    Probably simplest to write an `Answer` that counts its invocations, and throws the exception if it's the thirtiest invocation. Sing out if that's not clear, and I'll write a fuller answer. – Dawood ibn Kareem May 21 '18 at 02:18
  • see https://stackoverflow.com/questions/8088179/using-mockito-with-multiple-calls-to-the-same-method-with-the-same-arguments/33698670 – Shanu Gupta May 21 '18 at 03:01

1 Answers1

4

You can try:

when(someMock.someMethod()).thenAnswer(new Answer() {
    private int count = 0;
    public Object answer(InvocationOnMock invocation) {
        if (count++ == 30){
            ...do something...
        }
        ...do something...
    }
});
Duong Anh
  • 529
  • 1
  • 4
  • 21
  • Final working method ("dao" is mock object): @Test(expected = ArithmeticException.class) public void AAA() throws SQLException { doAnswer(new Answer() { private int count = 0; @Override public Object answer(InvocationOnMock invocation) throws Throwable { if (++count == 30) { throw new ArithmeticException(); } return invocation; } }).when(dao).nothing(); for (int i = 0; i < 30; i++) { dao.nothing(); } } – user7968180 May 21 '18 at 03:51
  • 1
    Yes, for void method you can use: doAnswer(..).when(mockObject).voidMethod(args...). – Duong Anh Dec 21 '18 at 02:10