简体   繁体   中英

How to verify that exception was thrown by mock method?

How to verify that exception was thrown by mock method in code below?
It simply throw exception on checking method without ending verify.

// import mockito

...

@Test
public void someTest() throws Exception {
    // reset and setup mock
    reset(mock);
    when(mock.getObj(Matchers.anyLong()))
        .thenReturn(new Obj());
    when(mock.save(any(Obj.class)))
        .thenThrow(new RuntimeException("Error!"));
    // work where mock is used (it throws no exceptions)
    work();
    // verify that exception on mock.save() was thrown
    // ! PROBLEM HERE: exception throws right here and verify doesn't end  
    verify(mock, times(1)).save(any(Obj.class));
}

UPD
work() - only sends message to Kafka-consumer (which is being tested) which works on embedded Kafka-server.
mock - mocks some object in consumer logic.

In this case, checking out the exception is an ADDITIONAL check for checking a certain branch of the consumer algorithm (other asserts not important (deleted): they checks that message was worked).

I assume that "work" is throwing the RuntimeException?

If so, you could surround your work() method with a try catch, for example...

try {
    work();
    Assert.fail("Did not catch expected exception!");
} catch(RuntimeException ex) {
    // Expected
}

verify(mock, times(1)).save(any(Obj.class));

If not, you may need to post the code under the test to let us see what is happening...


EDIT: Still not 100% sure what you mean, this test passes for me...

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class Stack {
    @Mock
    private Mocked mock;

    @Test
    public void someTest() throws Exception {
        reset(mock);
        when(mock.getObj(Matchers.anyLong()))
                .thenReturn(new Obj());
        when(mock.save(any(Obj.class)))
                .thenThrow(new RuntimeException("Error!"));
        work();
        verify(mock, times(1)).save(any(Obj.class));
    }

    private void work() {
        Obj obj = mock.getObj(1234L);

        try {
            mock.save(obj);
        } catch(Exception ex) {
            // Bad things happened
        }
    }

    private interface Mocked {
        Obj getObj(long l);

        Obj save(Obj obj);
    }

    public static class Obj {

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM