繁体   English   中英

如何使用 Mockito 和 catch-exception 断言 void 方法抛出异常?

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

我正在尝试测试此方法:

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

这是 findLoggedInUser:

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

这是我到目前为止的测试:

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

    // when
    sut.deleteCurrentlyLoggedInUser(principalStub);

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

那么我如何在这里使用catch-exception捕获异常呢? 我正在测试的方法返回 void,我似乎无法找到断言发现异常的方法。

编辑:我知道我可以使用: @Test(expected = UserAlreadyDeletedException.class)但我想将我的整个项目切换到 catch-exception 因为它要好得多并且在 @Test 中使用 expected 不是很合理。

我从未听说过 catch-exception,但它看起来并不像一个最新的库:主要源代码的最后一次更新(在撰写本文时)是在 2015 年 5 月 3 日

如果您使用的是 Java 8,并且可以使用 JUnit 4.13 或更高版本,则可以使用assertThrows

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

如果您打算将所有代码迁移到某些东西上,这似乎是一个更好的长期赌注。

使用规则可能对您有用?

规则允许非常灵活地添加或重新定义测试类中每个测试方法的行为。 测试人员可以重用或扩展下面提供的规则之一,或者编写自己的规则。

您可以在此处阅读有关 junit4 的这一简洁功能的更多信息:

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

例子:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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