如何在匿名方法中包装属性赋值
本文关键字:包装 属性 赋值 方法 | 更新日期: 2023-09-27 18:30:57
基本上,我创建了一个自定义的 Assert 方法,该方法断言抛出了异常。这对我正在做的一些单元测试来说很方便
除非它将操作作为参数(显然),但不会将属性分配作为操作。
如何将属性赋值包装在匿名函数中?
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
AssertException.DoesntThrow<Exception>(() => { robot.Instructions = "RLRLMLR"; });
这将创建一个 lambda 表达式,该表达式不()
参数,并在大括号内执行代码。