Back to Nunit

NUnit2040

docs/articles/nunit-analyzers/NUnit2040.md

latest2.0 KB
Original Source

NUnit2040

Non-reference types for SameAs constraint

TopicValue
IdNUnit2040
SeverityError
EnabledTrue
CategoryAssertion
CodeSameAsOnValueTypesAnalyzer

Description

The SameAs constraint always fails on value types as the actual and the expected value cannot be the same reference.

Motivation

csharp
var expected = Guid.Empty;
var actual = expected;

Assert.That(actual, Is.SameAs(expected));

As Guid is a struct, actual will be a copy of expected but not have the same reference.

How to fix violations

Replace Is.SameAs with Is.EqualTo.

csharp
var expected = Guid.Empty;
var actual = expected;

Assert.That(actual, Is.EqualTo(expected));
<!-- start generated config severity -->

Configure severity

Via ruleset file

Configure the severity per project, for more info see MSDN.

Via .editorconfig file

ini
# NUnit2040: Non-reference types for SameAs constraint
dotnet_diagnostic.NUnit2040.severity = chosenSeverity

where chosenSeverity can be one of none, silent, suggestion, warning, or error.

Via #pragma directive

csharp
#pragma warning disable NUnit2040 // Non-reference types for SameAs constraint
Code violating the rule here
#pragma warning restore NUnit2040 // Non-reference types for SameAs constraint

Or put this at the top of the file to disable all instances.

csharp
#pragma warning disable NUnit2040 // Non-reference types for SameAs constraint

Via attribute [SuppressMessage]

csharp
[System.Diagnostics.CodeAnalysis.SuppressMessage("Assertion",
    "NUnit2040:Non-reference types for SameAs constraint",
    Justification = "Reason...")]
<!-- end generated config severity -->