There is another way to test exceptions with nunit !!

Source: Internet
Author: User

There is another way to test exceptions with nunit !!

Nunit is an open-source unit testing tool dedicated to testing C # code. Of course, this excellent tool is free of charge. You can get this tool from the http://www.nunit.org. As a unit test tool, it certainly provides the test exception function. Using this tool, people usually use the following method to test whether the method can correctly throw an exception:

[Test]

Public void testinsertvertex ()

{

Verticescollection Vc = new verticescollection ();

Vertex v = NULL;

VC. insertvertex (1, V );

}

The verticescollection. insertvertex () method is tested. This method inserts an element into a specified position. If its second parameter receives a null value, it will throw an argumentoutofrangeexception. However, once the expected exception is thrown, the remaining code in the test method will be skipped. This is a big headache. To avoid this situation, we may wish to use the following method for testing to achieve the same effect.

[Test]

Public void testinsertvertex ()

{

Verticescollection Vc = new verticescollection ();

System. argumentoutofrangeexception exception = NULL;

Try

{

Vertex v = NULL;

VC. insertvertex (-1, V );

}

Catch (argumentoutofrangeexception ex)

{

Exception = ex;

}

Assert. arenotequal (null, exception );

Assert. areequal (typeof (argumentoutofrangeexception), exception. GetType ());

}

It is very simple. Capture the expected exception using the try/catch statement, and then use assert. areequal to determine whether the exception is the expected exception. The above is the case where an exception is thrown. If you expect not to throw an exception, you should:

System. argumentoutofrangeexception exception2 = NULL;

Try

{

VC. insertvertex (VC. Number-1, new vertex ("AAA "));

}

Catch (argumentoutofrangeexception ex)

{

Prediction2 = ex;

}

Assert. areequal (null, exception2 );

If no exception exists, prediction2 should be null.

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.