David
David

Reputation: 218960

What Block Isn't Covered?

Visual Studio 2013 is showing my code coverage for this (simplified for this example) object as missing a block:

code coverage

As far as I know, that if should have exactly two states. Pass and fail. And debugging my tests shows that each of those conditions is executed once. Specifically with these two tests:

[TestMethod]
public void CanNotHaveNegativeServiceWindow()
{
    // arrange
    var request = new CreateCaseRequest
    {
        ServiceWindowStart = new DateTime(2014, 12, 31, 12, 00, 00),
        ServiceWindowEnd = new DateTime(2014, 12, 31, 11, 00, 00)
    };

    // act
    var result = request.GetValidationErrors();

    // assert
    Assert.AreEqual(1, result.Count());
}

[TestMethod]
public void CanHaveServiceWindow()
{
    // arrange
    var request = new CreateCaseRequest
    {
        ServiceWindowStart = new DateTime(2014, 12, 31, 11, 00, 00),
        ServiceWindowEnd = new DateTime(2014, 12, 31, 12, 00, 00)
    };

    // act
    var result = request.GetValidationErrors();

    // assert
    Assert.AreEqual(0, result.Count());
}

One test validates the positive result of that specific if condition, the other validates the negative result. What block isn't covered? What logical condition exists that I'm missing?

Upvotes: 3

Views: 1789

Answers (2)

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

Light beige doesn't mean the code has not been covered. It means it's been only partially covered. Your ServiceWindowStart and ServiceWindowEnd are nullable. But you test them only with values. And you doesn't test for equality. Adding test for null values and for the case when they are equal should cover missing test cases.

Another possible reason of this result can be related to the fact that code coverage is performed on IL code and not on C# code. And the IL equivalent may not be fully covered or the structure of the code may not be preserved.

Optimizing your build may solve the problem. Go to Solution Explorer -> Properties -> Build tab -> Check the "Optimize code" check box.

Run the code analysis with this option selected.

Here's interesting blog post that covers this topic: http://blogs.msdn.com/b/ddietric/archive/2009/10/21/all-the-wonderful-colors-of-code-coverage.aspx

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

When you compare Nullable<T> values, C# compiler creates additional checks to see that the Nullable<T>s have values. These checks will always come out the same way in your code, because you have already done all the null checking explicitly.

Changing the condition to

if (ServiceWindowStart.Value > ServiceWindowEnd.Value)

should fix this problem.

Upvotes: 3

Related Questions