I have been on this problem for hours but couldn't get close to solution. Any help will be appreciated.
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;
}
Here, a user is going to enter a number, and if the number is not divisible by 1000, it throws an exception.
void validateTheEnteredAmount(){
final String INVALID_NUMBER = "1234";
InputStream in = new ByteArrayInputStream(INVALID_NUMBER.getBytes());
System.setIn(in);
assertThat(Application.enterTheAmount()).
isInstanceOf(IllegalArgumentException.class);
}
And I want to know when invalid number is entered, illegalArgumentException is thrown. I used assertThat method & isInstanceOf methods to validate. but for some reason, the test keeps failing.. Anyone with clues, please help
i used inputStream to store the number into the scanner. On the console, it shows that illegalargumentexception is thrown, but the test fails..
CodePudding user response:
You should use assertThrows
to check this.
assertThrows(IllegalArgumentException.class, () -> Application.enterTheAmount());
This will assert that the method throws an exception. If it doesn't, the test will be considered as failed.
CodePudding user response:
In the same situation I added a variable with Class
type :
private Class exceptionClass;
And I will initialize it in a catch
block as below:
public void updateBalance() {
try {
Account account = accountRepository.findById(id).get();
account.setBalance(balance);
accountRepository.save(account);
} catch (Exception e) {
exceptionClass = e.getClass();
}
}
And I wrote a method for my class that will check the result like below:
boolean hasObjectOptimisticLockingFailure() {
return this.exceptionClass == ObjectOptimisticLockingFailureException.class;
}
Then in my test method I checked it with below assertion statement:
assertTrue(account1.hasObjectOptimisticLockingFailure()
|| account2.hasObjectOptimisticLockingFailure());
I think you can do the same for your codes!!