[英]Lambdas and delegate types in NUnit tests: compiler errors
我正在写一些单元测试。 直接从NUnit的文档中获取 ,我应该能够做到这样的事情:
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()));
显然,我有两个解决方法,但我正在努力了解这里发生了什么。 为什么我new
了一个ExecutedRoutedEventArgs
在创建一个委托参数而不是其他的拉姆达。
更有趣的是,在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
{
}
}
我没有NUnit来验证,但可能是你需要显式地将Lambda强制转换为Delegate
以强制适当的重载解析:
Assert.That((Action)(()=>viewModel.SaveCommand_Exec(this, new ExecutedRoutedEventArgs())),
Throws.Nothing);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.