Issue
I'm trying to learn how to do JUnit testing but I'm stuck when it comes to throwing exceptions and all that. I really know nothing about all this. I've tried googling it but nothing that comes up is specific enough and I'm too uninformed to be able to apply it to my exact situation.
private int grade;
public void setGrade(int grade) throws Exception {
if (grade <= 100 && grade >= 0){
this.grade = grade;
}
else throw new IllegalArgumentException("Grade must be between 0 and 100 inclusive");
}
So I guess I just want to know how to test for the Exception. I don't know which assert to use or anything. To prove I've tried, this is what I've done:
@Test
void setGrade() throws Exception {
percentageGrade.setGrade(100);
assertEquals(100, this.percentageGrade.getGrade());
percentageGrade.setGrade(80);
assertNotEquals(100, this.percentageGrade.getGrade());
percentageGrade.setGrade(101);
assertThrows(IllegalArgumentException.class,() -> {
throw new IllegalArgumentException("Grade must be between 0 and 100 inclusive");
});
}
While waiting I've found this online but I don't understand what's happening. But the test passes.
@Test
void setGrade() throws Exception {
Exception thrown = assertThrows(Exception.class, () -> percentageGrade.setGrade(101), "Grade must be between 0 and 100 inclusive");
assertTrue(thrown.getMessage().contains("Grade must be between 0 and 100 inclusive"));
}
But I have no idea what I'm doing and the test fails anyway, at percentageGrade.setGrade(101);
Solution
You have to call the throwing method inside the assert:
assertThrows(IllegalArgumentException.class,() -> {
percentageGrade.setGrade(101);
});
Now you ensure with the assert, that setGrade
is throwing an IllegalArgumenException
.
Edit: To check the content of the thrown exception you can do the assignment to a variable:
Exception thrown = assertThrows(IllegalArgumentException.class,() -> {
percentageGrade.setGrade(101);
});
assertEquals("Grade must be between 0 and 100 inclusive", thrown.getMessage());
Answered By - Timo
Answer Checked By - Timothy Miller (JavaFixing Admin)