JUNIT4 Test exception

Source: Internet
Author: User

In some cases, we conclude that the target method throws an exception and how to handle it.

Using JUnit tests to throw exceptions, I summed up 3 ways to see the code:

Import static org.junit.assert.fail;import org.junit.rule;import org.junit.test;import  org.junit.rules.ExpectedException;/** *  test anomalies  *  *  @author  WEI.SS  *  */public class ExceptionTest {//  rule annotations, added on the public property, and attributes are implemented directly or indirectly org.junit.rules.testrule@rulepublic expectedexception expectedexception =  Expectedexception.none ();//  common Practice @testpublic void test1 ()  {try {//  impersonation throws exception if   ("AAA". Equals ("AAA")  {//  if no exception is thrown, the test will not pass throw new runtimeexception ();}   Normally, the code should not be executed here to fail ("Normally, the code should not be executed here");}  catch  (exception e)  {}}//  Specifies the exception @test (expected = ) that is expected to be thrown by using the properties of the annotation @test expected Runtimeexception.class) Public void test2 ()  {//  If no exception is thrown, the test will not pass through the throw new  RuntimeException ();} @Testpublic  void test3 ()  {//  expect to throw RuntimeException exception Expectedexception.expect ( RuntimeexceptIon.class);//  If no exception is thrown, the test will not pass throw new runtimeexception ();}} 


JUNIT4 Test exception

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.