Lambda 表达式的代码覆盖率
我在整个代码中看到一种模式,其中 lambda 表达式显示为未包含在代码覆盖范围内,调试器确实单步执行代码并且没有条件块。
public CollectionModel()
{
List<Language> languages = LanguageService.GetLanguages();
this.LanguageListItems =
languages.Select(
s =>
new SelectListItem { Text = s.Name, Value = s.LanguageCode, Selected = false }). // <-- this shows as not covered
AsEnumerable();
}
这有点奇怪。有什么想法吗?
I'm seeing a pattern throughout my code where the lambda expression is showing as not covered in code coverage, the debugger DOES step through the code and there are no conditional blocks.
public CollectionModel()
{
List<Language> languages = LanguageService.GetLanguages();
this.LanguageListItems =
languages.Select(
s =>
new SelectListItem { Text = s.Name, Value = s.LanguageCode, Selected = false }). // <-- this shows as not covered
AsEnumerable();
}
It is somewhat odd. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您进行单元测试时,如果您有一个方法返回您描述为 LanguageListItems 的列表,您可以在单元测试中执行此操作:
任何 dto 属性的每个断言都将执行 lambda 表达式,然后它将显示为覆盖。
When you are making the unit tests, if you have a method that returns the list you described as LanguageListItems, you can do this in the unit test:
Each Assert of any of the dto's property will execute the lambda expression and then it will appear as covered.
我认为你的意思是调试器没有跨过指定的行;对吗?
如果这是您的问题,那么答案是,至少在这种特殊情况下,您看到的是延迟执行。
System.Linq 提供的所有 LINQ 扩展方法.Enumerable
表现出这种行为:即,lambda 语句本身内的代码不会在您定义它的行上执行。仅在枚举结果对象后才会执行该代码。将其添加到您发布的代码下方:
在这里,您将看到调试器跳回您的 lambda。
What I think you mean is that the debugger is not stepping over the indicated line; is that right?
If that's your question, then the answer is that, at least in this particular case, what you are seeing is deferred execution. All of the LINQ extension methods provided by
System.Linq.Enumerable
exhibit this behavior: namely, the code inside the lambda statement itself is not executed on the line where you are defining it. The code is only executed once the resulting object is enumerated over.Add this beneath the code you have posted:
Here, you will see the debugger jump back to your lambda.