基本上,我已经创建了一个自定义Assert方法,该方法声明抛出了异常。这对于我正在进行的某些单元测试来说非常方便
除了将Action作为参数(显然),但不会将属性赋值作为操作。
如何在匿名函数中包装属性赋值?
public static class AssertException
{
public static void DoesntThrow<T>(Action func) where T : Exception
{
try
{
func.Invoke();
}
catch (Exception e)
{
Assert.Fail("No exception was expected but exception of type "
+ e.GetType() + " with message " + e.Message + " was thrown");
}
}
public static void Throws<T>(Action func, string expectedMessage = "") where T : Exception
{
bool exceptionThrown = false;
try
{
func.Invoke();
}
catch ( Exception e )
{
Assert.IsTrue(e.GetType() == typeof(T), "Expected exception of type " + typeof(T)
+ " but type of " + e.GetType() + " was thrown instead");
if (!expectedMessage.Equals(""))
{
Assert.AreEqual(e.Message == expectedMessage, "Expected exception with message of "
+ expectedMessage + " but exception with message " + e.Message + " was thrown instead");
}
return;
}
Assert.Fail("Expected exception of type " + typeof(T) + " but no exception was thrown");
}
}
电话:
AssertException.DoesntThrow<Exception>(robot.Instructions = "RLRLMLR");
这给了我:
Error 2 The best overloaded method match for 'RobotWarsTests.AssertException.DoesntThrow<System.Exception>(System.Action)' has some invalid arguments C:\Users\User\Documents\Visual Studio 2012\Projects\RobotWars\RobotWarsTests\UnitTest1.cs 20 13 RobotWarsTests
答案 0 :(得分:2)
AssertException.DoesntThrow<Exception>(() => { robot.Instructions = "RLRLMLR"; });
这将创建一个不带参数()
的lambda表达式,并在大括号内执行代码。