There are two ways of doing this:
First, the use of expectedexception
Supported only on junit4.7. You can test not only the catch to an exception, but also the exception message.
Examples of use are as follows:
@Rule PublicExpectedException exception =Expectedexception.none (); @Test Public voidShouldthrowexceptionwhensumgivenonenegativenumber ()throwsException {exception.expect (Exception.class); Exception.expectmessage (Containsstring ("Negatives not allowed")); Exception.expectmessage (Containsstring ("-1")); Stringcalculator.calculate (" -1,1"); } Public Static intCalculate (String numbers)throwsException {Throw NewException ("Negatives not allowed:-1"); }
Precautions:
1. ExpectedException must be public
Second, the use of annotation
This can only be measured in the presence of anomalies, not the exception message
How to use:
@Test (expected = Exception. Class) publicvoidthrows Exception { Stringcalculator.calculate (" -1,-1"); }
Junit Test exception