我正在尝试使用带有 spring boot 2.6.2 的 junit5 来测试服务层,并且我想测试如果找不到帐户则抛出异常,
我写了下面的测试方法
@Test
void getUserAccountWithUserAccountNotFoundExceptionTest() {
/**
* TODO tried to to test it but getting this error
* Checked exception is invalid for this method
*/
when(this.systemUserRepository.findByEmailAddress(emailAddress)).thenThrow(UserAccountNotFoundException.class);
Assertions.assertThrows(UserAccountNotFoundException.class, ()->{
this.manageUserAccountService.getUserAccount(emailAddress);
});
}
服务实施片段
@服务
公共类 ManageUserAccountServiceImpl {
......
@覆盖
公共 UserAccountDto getUserAccount(String emailAddress) 抛出 UserAccountNotFoundException {
......
…………
}
…………
}
未找到用户帐户异常类
public class UserAccountNotFoundException extends UserAccountException {
public UserAccountNotFoundException() {
super();
}
public UserAccountNotFoundException(int errorCode, String errorMessage) {
super(errorCode, errorMessage);
}
public UserAccountNotFoundException(Throwable cause, boolean enableSuppression, boolean writableStackTrace,
int errorCode, String errorMessage) {
super(cause, enableSuppression, writableStackTrace, errorCode, errorMessage);
}
public UserAccountNotFoundException(Throwable cause, int errorCode, String errorMessage) {
super(cause, errorCode, errorMessage);
}
}
用户账户异常类
public class UserAccountException extends Exception {
/**
*
*/
private static final long serialVersionUID = -591169136507677996L;
protected ErrorInfoDto errorInfoDto;
public UserAccountException() {
super();
}
public UserAccountException(Throwable cause, boolean enableSuppression,
boolean writableStackTrace,int errorCode, String errorMessage) {
this.errorInfoDto = formErrorInfoDto(errorCode, errorMessage);
}
public UserAccountException(int errorCode,String errorMessage) {
this.errorInfoDto = formErrorInfoDto(errorCode, errorMessage);
}
public UserAccountException(Throwable cause,int errorCode, String errorMessage) {
this.errorInfoDto = formErrorInfoDto(errorCode, errorMessage);
}
private ErrorInfoDto formErrorInfoDto(int errorCode, String errorMessage) {
ErrorInfoDto errorInfoDto = null;
errorInfoDto = new ErrorInfoDto();
errorInfoDto.setErrorCode(errorCode);
errorInfoDto.setErrorMessage(errorMessage);
return errorInfoDto;
}
public ErrorInfoDto getErrorInfoDto() {
return errorInfoDto;
}
}
存储库界面
public interface SystemUserRepository extends JpaRepository<SystemUser, Long> {
long countByEmailAddress(String emailAddress);
long countByMobileNo(String mobileNo);
Optional<SystemUser> findByEmailAddress(String emailAddress);
}
Mockito
异常单独说明了这一点 - when(this.systemUserRepository.findByEmailAddress(emailAddress)).thenThrow(UserAccountNotFoundException.class);
行指示 Mockito 在调用 systemUserRepository.findByEmailAddress(...)
时抛出异常。
但是,
SystemUserRepository
的发布代码确实声明了该方法的任何已检查异常:Optional<SystemUser> findByEmailAddress(String emailAddress);
另请注意,
SystemUserRepository
通过给出Optional.empty()
而不是抛出异常来处理未找到用户的情况。