Interesting way to assert thrown exceptions in Spring Boot and AssertJ

You’re probably used to testing code that throws exceptions in either one of the following ways:

Using expected attribute of JUnit @Test  annotation, such as:

 @Test(expected = UserService.NoSuchUserException.class)
    public void deletesExistingUser() {
        final User existingUser = spy(new User());
        given(userRepository.findOne(eq("123"))).willReturn(existingUser);
        given(userRepository.save(eq(existingUser))).willReturn(existingUser);

        userService.deleteUser("123");

        verify(existingUser).setState(eq(User.State.DELETED));
    }

Continue reading

Advertisements