I must credit the author of this, found on Stack Overflow. Link here: http://stackoverflow.com/questions/113395/how-can-i-test-for-an-expected-exception-with-a-specific-exception-message-from
The class is as follows:
public static class ExceptionAssert
{
public static T Throws(Action action) where T : Exception
{
try
{
action();
}
catch (T ex)
{
return ex;
}
Assert.Fail("Exception of type {0} should be thrown.", typeof(T));
// The compiler doesn't know that Assert.Fail
// will always throw an exception
return null;
}
}
An example of a test that makes use of this class is below
[TestMethod] public void GetOrganisation_MultipleOrganisations_ThrowsException() { OrganizationList organizations = new Organizations(); organizations.Add(new Organization()); organizations.Add(new Organization()); var ex = ExceptionAssert.Throws
( () => organizations.GetOrganization()); Assert.AreEqual(MyRes.MultipleOrganisationsNotAllowed, ex.Message); }
No comments:
Post a Comment