开发者

Code Coverage on Lambda Expressions

开发者 https://www.devze.com 2023-01-16 11:37 出处:网络
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.

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 =>
        开发者_如何学C    new SelectListItem { Text = s.Name, Value = s.LanguageCode, Selected = false }). // <-- this shows as not covered
            AsEnumerable();
}

It is somewhat odd. Any ideas?


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:

foreach (var x in this.LanguageListItems)
{
    var local = x;
}

Here, you will see the debugger jump back to your 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:

var result = await controller.SomeAction();
var okObjectResult = Assert.IsType<OkObjectResult>(result);
var results = Assert.IsAssignableFrom<IEnumerable<YourDtoClass>>okObjectResult.Value);
Assert.NotNull(results);
Assert.All(results, dto => Assert.NotNull(dto.PendingItemCount));
Assert.All(results, dto => Assert.NotNull(dto.ApprovedItemCount));

Each Assert of any of the dto's property will execute the lambda expression and then it will appear as covered.

0

精彩评论

暂无评论...
验证码 换一张
取 消