Junit 4.7 Rule: Another way to assert exceptions (ExpectedException)

Source: Internet
Author: User

在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
    1. The expectedexception variable declaration for the @Rule annotation, which must be public
    2. @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
    3. Ensure that the method being tested is behind the expectedex.expectxxx () method, otherwise it cannot be verified
    4. 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.