Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JUnit Testing exception always fail? [duplicate]

I'm using JUnit 4.11.

Eclipse Version: Luna Service Release 2 (4.4.2)

I need do the exception test. The code maybe like this:

// src code
public void myMethod throws MyException {
    ...
    throw new MyException(msg);
    ...
}

// test code
@Test (expected = MyException.class)
public void testMyMethod() {
    try {
        myMethod();
        fail();
    } catch (MyException e) {
        assertEquals(expectedStr, e.getMessage());
    }
}

But the test always fail, where am i wrong?

like image 508
Jerikc XIONG Avatar asked May 22 '15 16:05

Jerikc XIONG


People also ask

How does JUnit handle multiple exceptions?

You would have to write a different unit test for each way the method can fail. So if the method legitimately throw two exceptions then you need two tests set up to force the method of throwing each exception. But under one set of data is can only fail in one way.

When a JUnit test fails What does it mean?

Example Failure When writing unit tests with JUnit, there will likely be situations when tests fail. One possibility is that our code does not meet its test criteria. That means one or more test cases fail due to assertions not being fulfilled.

Should JUnit tests throw exceptions?

The JUnit TestRunners will catch the thrown Exception regardless so you don't have to worry about your entire test suite bailing out if an Exception is thrown. This is the best answer.


1 Answers

When you provide an expected exception to the Test annotation, the test will only succeed if the exception expected is thrown from the test method. However, you catch the exception before it propagates out of the method.

It looks like you want to test the exception message too, so re-throw the exception e to satisfy the test. Depending on whether it's checked, you may need a throws clause on the method.

like image 144
rgettman Avatar answered Oct 10 '22 21:10

rgettman