我有一個方法:
public UserEntity authentication(final UserEntity auth)
throws AuthenticationException, EmailNotFoundException {
final AtomicReference<UserEntity> atomic = new AtomicReference<>();
this.repository
.findByEmail(auth.getEmail())
.ifPresentOrElse(
usr -> {
if (Objects.equals(usr.getPassword(), auth.getPassword())) {
atomic.set(usr);
} else {
throw new AuthenticationException();
}
},
() -> {
throw new EmailNotFoundException(auth.getEmail());
}
);
return atomic.get();
}
這是用戶授權測驗的樣子:
@Test
void userAuthentication_success() {
given(this.repository.findByEmail(this.user.getEmail()))
.willReturn(Optional.of(this.user));
assertThat(this.underTest.authentication(this.user))
.isInstanceOf(UserEntity.class)
.isEqualTo(this.user);
verify(this.repository)
.findByEmail(this.user.getEmail());
}
有沒有辦法檢查用戶輸入錯誤密碼的情況?
在我發送錯誤密碼的情況下,它不起作用,因為
在您檢查密碼之前given(this.repository.findByEmail(this.user.getEmail())).willReturn(Optional.of(this.user));會repository.findByEmail()回傳結果。
uj5u.com熱心網友回復:
你不需要這個強大的多行 lambda。在iflambda 運算式之外使用 -statement 比將其塞進 lambda 運算式要干凈得多。
AtomicReference除非您有意讓代碼的讀者感到困惑,否則無需使用復雜的邏輯。
三種情況:用戶不存在,用戶憑證錯誤,用戶資料有效。讓我們分別處理它們:
public UserEntity authentication(final UserEntity auth)
throws AuthenticationException, EmailNotFoundException {
UserEntity user = this.repository
.findByEmail(auth.getEmail())
.orElseThrow(() -> new EmailNotFoundException(auth.getEmail()));
if (Objects.equals(user.getPassword(), auth.getPassword())) {
throw new AuthenticationException();
}
return user;
}
要測驗是否按預期拋出例外,您可以使用assertThrows().
這是一個測驗檢查是否AuthenticationException會在用戶憑據不正確時拋出的示例:
@Test
void userAuthenticationFailure() {
assertThrows(AuthenticationException.class,
() -> this.underTest.authentication(UserWithWorngPassword),
"Wrong user password should trigger an Exception");
}
uj5u.com熱心網友回復:
首先,我會重構您的代碼以避免副作用:
public UserEntity authentication(final UserEntity auth)
throws AuthenticationException, EmailNotFoundException {
return this.repository
.findByEmail(auth.getEmail())
.map(usr -> {
if (!Objects.equals(usr.getPassword(), auth.getPassword())) {
throw new AuthenticationException();
}
return usr;
}).orElseThrow(() -> { throw new EmailNotFoundException(auth.getEmail()); });
}
然后,我沒有看到 mocking 的問題this.repository.findByEmail,我只是認為你讓它回傳了一個具有正確密碼的有效用戶。就像是:
given(this.repository.findByEmail(this.user.getEmail())).willReturn(Optional.of(this.user.withPassword("wrong password")));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507616.html
上一篇:使用測驗庫測驗Redux時出現此錯誤:警告:React.createElement:typeisinvalid:butgot:undefined
