Friday 22 June 2012

ShouldThrowException<T> Helper

Many unit test frameworks provide an assert wrapper for an expected exception such as the following in NUnit:

Assert.Throws<T>( code here );

Some frameworks like MS Test don’t and rely on the attributes on the test itself, rather than a specific line of code e.g.

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GivenConstructorWhenNameIsEmptyThenArgumentExceptionThrown()
{
code
}

If like me you prefer the more targeted nature of the latter so you can use the following code in your unit test project:

public static void ShouldThrowException<T>(Action action) where T : Exception
{
try
{
action();
}
catch (T)
{
return;
}

Assert.Fail("Expected exception did not occur");
}

Here is an example of its usage:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestHelperShouldThrowException.Tests
{
[TestClass]
public class PersonTests
{
[TestMethod]
public void GivenConstructorWhenNameIsFiveCharactersThenPersonIsCreated()
{
Person person = new Person("Tommy");
Assert.IsNotNull(person);
}

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GivenConstructorWhenNameIsEmptyThenArgumentExceptionThrown()
{
Person person = new Person("");
}

[TestMethod]
public void GivenConstructoWhenNameIsEmptyThenArgumentExceptionThrownUpdated()
{
Helper.ShouldThrowException<ArgumentException>(() => new Person(""););
}
}

class Person
{
public string Name { get; set; }

public Person(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("Invalid name value");

Name = name;
}
}
}

Source: https://github.com/stevenh77/ShouldThrowException

No comments:

Post a Comment