Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Coverage on Lambda Expressions

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?

like image 494
Rod Johnson Avatar asked Sep 13 '10 14:09

Rod Johnson


People also ask

How do you set code coverage?

To calculate the code coverage percentage, simply use the following formula: Code Coverage Percentage = (Number of lines of code executed by a testing algorithm/Total number of lines of code in a system component) * 100.

How do you test a lambda expression?

The first is to view the lambda expression as a block of code within its surrounding method. If you take this approach, you should be testing the behavior of the surrounding method, not the lambda expression itself. The only thing that the lambda expression in this body of code does is directly call a core Java method.

How many parameters does a lambda expression need?

The lambda expressions are easy and contain three parts like parameters (method arguments), arrow operator (->) and expressions (method body).


1 Answers

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.

like image 67
Dan Tao Avatar answered Oct 01 '22 08:10

Dan Tao