I need to write a unit test for the next function and I saw I can use [ExpectedException]
this is the function to be tested.
public static T FailIfEnumIs
ExpectedException
just asserts that exception of specified type will be thrown by test method:
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE
// EXECUTE
// NO ASSERT!!
}
If you want to assert other parameters of exception, then you should use try..catch
in your test method:
[TestMethod]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE
try
{
// EXECUTE
Assert.Fail()
}
catch(Exception exception)
{
// ASSERT EXCEPTION DETAILS
}
}
You can write your own method for asserting exception was thrown to avoid repeating same test code over and over again:
public TException AssertCatch(Action action)
where TException : Exception
{
try
{
action();
}
catch (TException exception)
{
return exception;
}
throw new AssertFailedException("Expected exception of type " +
typeof(TException) + " was not thrown");
}
Usage:
var exception = AssertCatch(() => /* EXECUTE */);
Assert.AreEqual("foo", exception.Message);