Wednesday, May 25, 2016

Visual Studio Unit Tests: Handling Exceptions

In a previous post the development of Unit Tests was presented (Visual Studio: Developing Unit Tests) but in each case the methods under test returned a value and none of the methods under test threw exceptions. This post will present how to test exceptions using ExpectedException attribute from the Microsoft.VisualStudio.TestTools.UnitTesting namespace.

public bool IsItSo(string data)
{
  if (data == null)
  {
    throw new ArgumentNullException();
  }

  if ((data == "A") || (data == "B") || (data == "C"))
  {
    return true;
  }

  else
  {
    return false;
  }
}

The previous post, Visual Studio: Developing Unit Tests, demonstrated how to create unit tests so to test the passing a null value to the IsItSo method, a new test method can be created:

[TestMethod]
public void IsItSoNullException()
{
  Worker worker = new Worker();
  bool result;

  result = worker.IsItSo(null); 
  Assert.IsTrue(result); 
}

This test can be run from Test Explorer displayed using Visual Studio’s Test menu’s Windows | Test Explorer option: Running the test method, IsItSoNullException creates a failed test due to the exception:


The behavior that the IsItSo method will throw an exception is a known behavior. To test this the ExpectedException  attribute is added to the IsItSoNullException  test method:

[ExpectedException(typeof(ArgumentNullException))]
[TestMethod]
public void IsItSoNullException()
{
  Worker worker = new Worker();
  bool result;

  result = worker.IsItSo(null);
  Assert.IsTrue(result);
}

Running the test method, IsItSoNullException, results is a successful test run:



The constructor for the ExpectedException attribute used above is as follows:

public ExpectedExceptionAttribute(
Type exceptionType)

The type passed into the constructor is the type of the exception expected. If a different exception is thrown in the test method then the test will fail:



If no exception is is thrown by the test method adorned with the ExpectedException attribute then the test fails:



The ExpectedExceptionAttribute class exposes a second constructor signature:

public ExpectedExceptionAttribute(
Type exceptionType,
string noExceptionMessage)

The second parameter is supposed to display when the test fails. This behavior does not work in Visual Studio but according the postings on the web, this works when running MSTest or VSTest. So if developers need to convey information to QA with regards to test failure, this is the mechanism that should be used.



No comments :

Post a Comment