我正在写一些单元测试。直接取自 NUnit 的 documentation ,我应该能够做这样的事情:
Assert.That( SomeMethod, Throws.ArgumentException );
在测试方法中,这不会编译:
Assert.That(()=>viewModel.SaveCommand_Exec(this, new ExecutedRoutedEventArgs()),
Throws.Nothing);
// Compiler error:
// Cannot convert lambda expression to type 'bool'
// because it is not a delegate type
但这会:
ExecutedRoutedEventArgs e = new ExecutedRoutedEventArgs();
Assert.That(() => viewModel.SaveCommand_Exec(this, e), Throws.Nothing);
这也是:
Assert.DoesNotThrow(()=>viewModel.SaveCommand_Exec(this,
new ExecutedRoutedEventArgs()));
显然,我有两个解决方法,但我有点难以理解这里发生了什么。为什么我可以在 lambda 中new
创建一个 ExecutedRoutedEventArgs
来创建一个委托(delegate)参数而不是另一个。
更有趣的是,在 lambda 外部而不是内部创建 EventArgs
对象到底有什么区别?我意识到这会创建一个闭包,但我不明白这会如何更改匿名方法的签名。
我正在使用 VS2013,目标是 .net 4.0
最佳答案
我无权访问您在示例中使用的确切类,但以下非常相似的代码在针对 .NET 4 的 VS 2013 中编译并运行良好。您使用的是 NUnit 2.6.3 吗?此外,您正确地确定了在 lambda 外部创建 ExecutedRoutedEventArgs
实例与在其内部创建实例之间的唯一区别:一个闭包。
using NUnit.Framework;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main()
{
var viewModel = new ViewModel();
Assert.That(() => viewModel.SaveCommand_Exec(null, new ExecutedRoutedEventArgs()), Throws.Nothing);
}
}
public class ViewModel
{
public bool SaveCommand_Exec(object sender, ExecutedRoutedEventArgs e)
{
return true;
}
}
public class ExecutedRoutedEventArgs
{
}
}
关于c# - NUnit 测试中的 Lambda 和委托(delegate)类型 : compiler errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22101283/