coverlet-coverage / coverlet

Cross platform code coverage for .NET
MIT License
2.93k stars 385 forks source link

[BUG] HasValue of Nullable<T> is not taken into account #1644

Open mu88 opened 3 months ago

mu88 commented 3 months ago

Describe the bug After ensuring that an instance of Nullable<T> is not null via .HasValue, coverlet still assumes the instance to be nullable and therefore the branch coverage indicates a missing test branch.

To Reproduce

public static class ServiceExtensions
{
    public static bool IsInPast(this IService service)
    {
        Nullable<TimeOnly> timeFromService = service.GetTime();
        if (!timeFromService.HasValue) return true;

        bool isInPast = timeFromService < TimeOnly.FromDateTime(DateTime.UtcNow);

        return isInPast;
    }
}

Here you find a complete repro case.

Expected behavior

Branch coverage is 100% for the line var isInPast = timeFromService < TimeOnly.FromDateTime(DateTime.UtcNow);.

Actual behavior

Coverlet complains that only 1 out of 2 branches is tested as it assumes that timeFromService can still be null:
image

Configuration (please complete the following information): Please provide more information on your .NET configuration:

Additional context

Using timeFromService.Value rather than timeFromService can be used as a workaround.

:exclamation: Please also read Known Issues