Issue
I had the question some minutes before but I want to try something else..
For Example I have this method:
//inside Number.java
public static int add(int nr1, int nr2) {
return nr2 + nr2;
}
As you see I return number2 + number2
In my Test I use that it would throw the error that it was expected 9 instead of the number which was calculate in the main method.
@Test
public void test() throws Exception {
int nr1 = 4;
int nr2 = 5;
int sum = Number.add(nr1, nr2);
assertEquals(9, sum);
}
I tried this now to get an message if the program fails but it doesn´t with fail..
@Test
public void test() throws Exception {
int nr1 = 4;
int nr2 = 5;
int sum = Number.add(nr1, nr2);
try {
assertEquals(9, sum);
}catch(Exception e) {
fail("Are you sure you calculate the right numbers?");
}
}
But the program is only showing me the AssertionError not the Message in fail()
I know now that I can use it this way:
assertEquals("...",9,sum);
but I don't want this AssertionError:
expected:<> but was <>
at the end
Solution
An AssertionError
extends Error
which implements Throwable
. Your
catch(Exception e)
is useless because the AssertionError
is not an Exception
.
Catch it directly using catch(AssertionError e)
if you must, but usually Error
s are not supposed to be caught.
If you really want to force a call to fail
, avoid the assertEquals
and just use
if(sum != 9) {
fail("Are you sure you calculate the right numbers?");
}
which avoids the AssertionError altogether.
Answered By - f1sh
Answer Checked By - David Marino (JavaFixing Volunteer)