【问题标题】:Mockito How to mock and assert a thrown exceptionMockito 如何模拟和断言抛出的异常
【发布时间】:2021-08-30 10:03:19
【问题描述】:

我有这个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);

    }

但我有这个错误:

 unnecessary Mockito stubbings

我也试过了:

   @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);
        

    }

【问题讨论】:

    标签: java spring junit mocking mockito


    【解决方案1】:

    问题是你正在存根,但没有真正测试任何东西。如果你没有测试任何东西,那么就不需要存根。这就是为什么你有不必要的 Mockito 存根。

    我假设你想测试你的SecurityManagerService。如果您想这样做,您需要创建一个实例或拥有该类型的 bean,但不是模拟。然后你调用你想要测试的方法并断言你得到了预期的结果。

    如果你希望得到一个异常,你可以这样测试它:

    JUnit4,只是增强你@Test注解:

    @Test(expected=SecurityException.class)
    

    JUnit 5:

    @Test
    void testExpectedException() {
      Assertions.assertThrows(SecurityException.class, () -> {
        //Code under test
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 2019-09-03
      相关资源
      最近更新 更多