microsoft / testfx

MSTest framework and adapter
MIT License
723 stars 254 forks source link

Incorrect nullability for Assert.IsNotNull method in v3.0.0 #1444

Closed NoahStolk closed 1 year ago

NoahStolk commented 1 year ago

Describe the bug

Assert.IsNotNull does not specify that the value parameter will never be null if the method returns. This used to work in version 2.x.x. Is there a reason for this? It seems that the object? value parameter needs to be annotated with the [NotNullAttribute]. The attribute is there in 2.2.10, but in 3.0.0 it's missing.

Steps To Reproduce

  1. Add an MSTest project using MSTest 3.0.0:
<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <IsPackable>false</IsPackable>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="coverlet.collector" Version="3.1.2" />
        <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
        <PackageReference Include="MSTest.TestAdapter" Version="3.0.0" />
        <PackageReference Include="MSTest.TestFramework" Version="3.0.0" />
    </ItemGroup>

</Project>
  1. Add a test:
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Example;

[TestClass]
public class Tests
{
    [TestMethod]
    public void Test1()
    {
        string? test = MethodToTest();
        Assert.IsNotNull(test);
        Assert.AreEqual(3, test.Length); // CS8602: Dereference of a possibly null reference.

        string? MethodToTest()
        {
            return null; // Or anything else
        }
    }
}

Expected behavior

No warnings.

Actual behavior

The code emits diagnostic CS8602 while it is perfectly valid. test cannot be null because Assert.IsNotNull will throw if it is.

Evangelink commented 1 year ago

Duplicates #1438