Why does JUnit Testing exception always fail?

I am using JUnit 4.11.

Eclipse Version: Luna Service Release 2 (4.4.2)

I need an exception test. The code may look 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 fails, where am I wrong?

+6
source share
1 answer

When you provide the expected exception for the Test annotation, the test will only succeed if the expected exception is selected from the test method. However, you encounter an exception before it propagates outside the method.

It looks like you want to test the exception message too, so throw exception e again to run the test. Depending on whether it is tested, you may need a throws in a method.

+4
source

Source: https://habr.com/ru/post/987762/


All Articles