nunit.analyzers icon indicating copy to clipboard operation
nunit.analyzers copied to clipboard

[improvement] NUnit2010 should provide a different suggestion for null comparison

Open Bartleby2718 opened this issue 1 year ago • 1 comments

Suppose the following:

string? nullString = null;
string? nonNullString = "nonNullString";
int? nullInt = null;
int? nonNullInt = 42;

Then, NUnit2010 flags the following assertions and proposes some fixes (as of NUnit.Analyzers 4.2.0):

// Assert.That(nullString, Is.EqualTo(null)); is proposed for the following two:
Assert.That(nullString is null);
Assert.That(nullString == null);

// Assert.That(nonNullString, Is.Not.EqualTo(null)); is proposed for the following two:
Assert.That(nonNullString is not null);
Assert.That(nonNullString != null);

// Assert.That(nullInt, Is.EqualTo(null)); is proposed for the following two:
Assert.That(nullInt is null);
Assert.That(nullInt == null);

// Assert.That(nonNullInt, Is.Not.EqualTo(null)); is proposed for the following two:
Assert.That(nonNullInt is not null);
Assert.That(nonNullInt != null);

I don't know how Is.EqualTo is implemented under the hood, but I'm pretty sure Is.Null or Is.Not.Null should be used for either half or all of the fixes, depending on how Is.EqualTo works.

Bartleby2718 avatar Jun 02 '24 01:06 Bartleby2718

The actual generated code is correct, but indeed it could improve the code more by checking the actual argument tested and generated Is.Null for null and also Is.Zero for 0.

manfred-brands avatar Jun 02 '24 02:06 manfred-brands

Currently, NUnit2010 changes Assert.That(nonNullInt is not null); into Assert.That(nonNullInt, Is.Not.EqualTo(null)); and then we can use NUnit4002 to change it into Assert.That(nonNullInt, Is.Not.Null); (and similarly for the other cases, but I agree that NUnit2010 could just as well combine both refactorings into one.

mikkelbu avatar Jun 02 '25 20:06 mikkelbu