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.