Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why `fail` inside `catch(Exception ex)` handling `assertEquals` is not called?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 Errors 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading