Skip to content
Advertisement

Mockito How to mock and assert a thrown exception

I have this junit:

@RunWith(MockitoJUnitRunner.class)
public class SecurityManagerServiceTest  {

    @Mock
    private SecurityManagerService securityManagerService = mock(SecurityManagerService.class);

    @Test
    public void testRequireAll() {
        when(securityManagerService.loggerUser()).thenReturn(fakeUser());
        doCallRealMethod().when(securityManagerService).requireRight(anyString());
        //given(securityManagerService.restoreRight("a")).willThrow(SecurityException.class);
        when(securityManagerService.restoreRight("a")).thenThrow(SecurityException.class);

    }

but I have this error:

 unnecessary Mockito stubbings

I also tried:

   @Mock
    private SecurityManagerService securityManagerService = mock(SecurityManagerService.class);

    @Test
    public void testRequireAll() {
        when(securityManagerService.loggerUser()).thenReturn(fakeUser());
        doCallRealMethod().when(securityManagerService).requireRight(anyString());
        given(securityManagerService.restoreRight("a")).willThrow(SecurityException.class);
        

    }

Advertisement

Answer

The problem is that you are stubbing, but not really testing anything. And if you are not testing anything, then there is no need for stubbing. That’s why you have unnecessary Mockito stubbings.

I assume that you want to test your SecurityManagerService. If you want to do that, you need to create an instance or have a bean of that type, but not a mock. Then you call the method that you want to test and assert that you get the expected result.

If you expect to get an exception you can test it like this:

JUnit4, just enhance you @Test annotation:

@Test(expected=SecurityException.class)

JUnit 5:

@Test
void testExpectedException() {
  Assertions.assertThrows(SecurityException.class, () -> {
    //Code under test
  });
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement