我已經解決了這個問題幾個小時,但無法接近解決方案。任何幫助將不勝感激。
public static int enterTheAmount(){
int final LOTTO_PRICE = 1000;
int amount = Integer.parseInt(Console.readLine());
if(amount%LOTTO_PRICE!=0) throw new IllegalArgumentException();
return amount/LOTTO_PRICE;
}
在這里,用戶要輸入一個數字,如果該數字不能被 1000 整除,則會引發例外。
void validateTheEnteredAmount(){
final String INVALID_NUMBER = "1234";
InputStream in = new ByteArrayInputStream(INVALID_NUMBER.getBytes());
System.setIn(in);
assertThat(Application.enterTheAmount()).
isInstanceOf(IllegalArgumentException.class);
}
我想知道當輸入無效數字時,會拋出非法引數例外。我使用 assertThat 方法和 isInstanceOf 方法進行驗證。但由于某種原因,測驗一直失敗..任何有線索的人,請幫忙
我使用 inputStream 將數字存盤到掃描儀中。在控制臺上,顯示拋出了非法引數例外,但測驗失敗..
uj5u.com熱心網友回復:
你應該用assertThrows這個來檢查。
assertThrows(IllegalArgumentException.class, () -> Application.enterTheAmount());
這將斷言該方法會引發例外。如果沒有,測驗將被視為失敗。
uj5u.com熱心網友回復:
在同樣的情況下,我添加了一個Class型別為的變數:
private Class exceptionClass;
我將在一個catch塊中初始化它,如下所示:
public void updateBalance() {
try {
Account account = accountRepository.findById(id).get();
account.setBalance(balance);
accountRepository.save(account);
} catch (Exception e) {
exceptionClass = e.getClass();
}
}
我為我的班級撰寫了一個方法,它將檢查如下結果:
boolean hasObjectOptimisticLockingFailure() {
return this.exceptionClass == ObjectOptimisticLockingFailureException.class;
}
然后在我的測驗方法中,我使用以下斷言陳述句對其進行了檢查:
assertTrue(account1.hasObjectOptimisticLockingFailure()
|| account2.hasObjectOptimisticLockingFailure());
我認為你可以為你的代碼做同樣的事情!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530450.html
