Testing Your Exceptions

You should write unit tests to verify your code behaves as expected in both positive and negative conditions. The positive conditions can be verified using the Assert methods, as discussed previously. However, many times you want to verify that your code returns the correct exception when you call or use it in a certain manner. In this case, you can decorate a test method with the ExpectedException attribute to test for specific error conditions.

The attribute takes the type of expected exception as a parameter. If the test method results in an exception being thrown and the type of that exception is as you defined in the attribute, the test is considered a success. If an exception is not thrown or an exception of a different type is thrown, the test is considered to have failed.

As an example, suppose that you want to test what happens when you try to create a new invoice that has incomplete details. In this case, your code might be written to throw a custom exception of type InvalidInvoiceException. You would then decorate your test method as follows.

[TestMethod()]
[ExpectedException(typeof(InvalidInvoiceException),
  "The Invalid Invoice Exception was not thrown.")]
public void Invoice_Is_Valid() {

  //create a bad, new invoice instance to test against
}

Notice that, in this code, if the exception is not thrown, there is an error message provided as the result of the test (The Invalid Invoice Exception was not thrown). This error message is an optional parameter of the ExpectedException attribute.

You can combine assertions with the ExpectedException attribute. In this case, both the assertions need to pass, and the exception needs to be thrown for the test method to be considered passed.


Note

The resulting exception must be of the same type as the expected exception. The resulting exception cannot, for instance, inherit from the expected exception. In this case, the test is considered to have failed.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset