[英]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.