简体   繁体   中英

How to assert that void method throws Exception using Mockito and catch-exception?

I'm trying to test this method:

public void deleteCurrentlyLoggedInUser(Principal principal) {
    if (findLoggedInUser(principal) == null) {
        throw new UserAlreadyDeletedException();
    }
    userRepository.delete(findLoggedInUser(principal));
}

Here is findLoggedInUser:

User findLoggedInUser(Principal principal) {
    return userRepository.findByUsername(principal.getName());
}

And here is my test so far:

@Test
public void shouldThrowExceptionWhenUserNotFound() {
    // given
    when(sut.findLoggedInUser(principalStub)).thenReturn(null);

    // when
    sut.deleteCurrentlyLoggedInUser(principalStub);

    // then
    catchException
    verify(userRepositoryMock, never()).delete(any(User.class));
}

So how do I catch exception using catch-exception here? Method that I'm testing returns void and I just can't seem to find a way to assert that exception was found.

EDIT: I know I could use: @Test(expected = UserAlreadyDeletedException.class) but I want to switch my whole project to catch-exception because it's much better and using expected in @Test is not very reasonable.

I've never heard of catch-exception, but it doesn't exactly seem like an up-to-date library: the last update to the main source code (at the time of writing) was on May 3 2015 .

If you're using Java 8, and can use JUnit 4.13 or later, you can use assertThrows :

assertThrows(
    UserAlreadyDeletedException.class,
    () -> sut.deleteCurrentlyLoggedInUser(principalStub));

If you're going to migrate all of your code to something, this seems like a better long-term bet.

It might be that using Rules is something that could work for you?

Rules allow very flexible addition or redefinition of the behavior of each test method in a test class. Testers can reuse or extend one of the provided Rules below, or write their own.

You can read more about this neat feature of junit4 here:

https://github.com/junit-team/junit4/wiki/Rules

Example:

public static class HasExpectedException {
    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    @Test
    public void throwsNullPointerException() {
            thrown.expect(NullPointerException.class);
            throw new NullPointerException();
    }
}

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