Code Coverage for Lambda Expressions

I see a pattern in all my code, where the lambda expression is shown as not covered in the code scope, the debugger MUST go 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(); } 

This is somewhat strange. Any ideas?

+7
c # lambda unit-testing code-coverage
source share
2 answers

I think you mean that the debugger does not step over the specified line; it is right?

If your question is, then the answer is that, at least in this particular case, you see delayed execution . All LINQ extension methods provided by System.Linq.Enumerable demonstrate this behavior: namely, the code inside the lambda operator itself does not execute on the line where you define it. Code is executed only after the resulting object is listed.

Add this under the code you posted:

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

Here you will see the debugger returning to your lambda.

+5
source share

When you do unit tests, if you have a method that returns a list that you described as LanguageListItems, you can do this in a 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 properties will execute a lambda expression, and then it will look like covered.

0
source share

All Articles