Java – why do JUnit testing exceptions always fail?
•
Java
How do you assert that a certain exception is throw in JUnit 4 tests? 32
Eclipse version: Luna service release 2 (4.4.2)
I need to do an exception test The code might 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 tests always fail. What's wrong with me?
Solution
When you provide the expected exception for the test annotation, the test will succeed only when the expected exception is thrown in the test method However, an exception is caught before transmitting the broadcast method
It seems that you also want to test the exception message, so re throw the exception e to meet the test requirements Depending on whether it is selected, you may need the throws clause of the method
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码