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 FailIfEnumIsNotDefined<T>(this T enumValue, string message = null)
where T:struct
{
var enumType = typeof (T);
if (!enumType.IsEnum)
{
throw new ArgumentOutOfRangeException(string.Format("Type {0} is not an Enum, therefore it cannot be checked if it is Defined not have defined.", enumType.FullName));
}
else if (!Enum.IsDefined(enumType, enumValue))
{
throw new ArgumentOutOfRangeException(string.Format("{1} Value {0} is not does not have defined value in Enum of type {0}. It should not be...", enumType.FullName, message ?? ""));
}
return enumValue;
}
and here would go the code to test the exceptions that are supposed to be threw
[TestMethod]
[ExpectedException(ArgumentOutOfRangeException(ArgumentException), "message")]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE
// EXECUTE
// ASSERT
}
I don't have idea have to make the assert for the exceptions either.
Assert.Throws()
instead ofExpectedException
, as this attribute makes the test pass if the exception occurred in any part of the test method code.Assert.Throws
allows to test exact place of code where the exception occurs. – TwingeMicrosoft.VisualStudio.TestTools.UnitTesting
namespace, seeExpectedExceptionAttribute
class. – GarrygarsonThrows
in my answer as well: https://mcmap.net/q/960416/-expectedexception-assert. – Flake