在Junit 4.7之后,加入了一种更容易断言异常以及异常信息的方法。
Exception handling
//Validation throws exception class, and error message Public class testexception {@Rule PublicExpectedException Expectedex = Expectedexception.none (); @Test Public voidTestvalidationexception () throws Validationexception {///assertion throws an exception, which must be preceded by the exception being thrown, or when the exception is thrown, the statement after the run is blocked. Expectedex.expect (Validationexception.class);//Assert the error message content. Note: The assertion information can be a string of the original error messageExpectedex.expectmessage ("is not passed");Throw NewValidationexception ("Password is not passed."); }}//Arbitrarily define an exception class class validationexception extends Exception{Validationexception (String msg) {Super(msg); }}
Expectmessage
The Expectedex.expectmessage method is useful when asserting multiple return information. For example, when validating a password, it is sometimes possible to assert two kinds of exceptions:
throw new Validationexception ("Password must contain letters and numbers");
throw new Validationexception ("Password cannot be greater than 16 bits");
Precautions
- The expectedexception variable declaration for the @Rule annotation, which must be public
- @Test, you cannot use other assertion methods, such as @test (Expected=validationexception.class), or you cannot test through, that is,
@Test (Expected=validationexception.class) and in the test method
The Expectedex.expectxxx () method cannot coexist simultaneously
- Ensure that the method being tested is behind the expectedex.expectxxx () method, otherwise it cannot be verified
- The arguments in Expectedex.expectmessage () can be either substring or matcher, which means that the assertion and can be substrings or regular expressions
Junit 4.7 Rule: Another way to assert exceptions (ExpectedException)