Skip to content

[Bug]: .Should().NotBeNull() assertion doesn't silence CS8602 - Dereference of a possibly null reference. #6673

Description

@radmorecameron

Description

When asserting that a value isn't null with .Should().NotBeNull(), the [NotNull] attribute isn't applied to the input causing the CS8602 warning when it shouldn't (when not using a null-forgiving operator after)

Expected Behavior

There should be no warning when accessing a property that could be null after doing a notnull assertion

Actual Behavior

There is a null reference warning

Steps to Reproduce

This should be enough to reproduce:

        [Test]
        [Arguments("1234")]
        [Arguments("123")]
        public async Task ExampleTest(string? result)
        {
            const int length = 3;
            await result.Should().NotBeNull();
            if (length == result.Length)
            {
                await ValidateThreeLength();
            }
            else
            {
                await ValidateOtherLength();
            }
        }

        private Task ValidateThreeLength() => Task.CompletedTask;
        private Task ValidateOtherLength() => Task.CompletedTask;

TUnit Version

1.65.63/1.65.63-beta

.NET Version

.NET 10

Operating System

Windows

IDE / Test Runner

Visual Studio

Error Output / Stack Trace

CS8602 - Dereference of a possibly null reference.

Additional Context

Only happens with Should assertions, not with Assert.NotNull

IDE-Specific Issue?

  • I've confirmed this issue occurs when running via dotnet test or dotnet run, not just in my IDE

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions