Skip to content

NUnit2007

Mikkel Nylander Bundgaard edited this page Apr 25, 2020 · 2 revisions

NUnit2007

Actual value should not be constant.

Topic Value
Id NUnit2007
Severity Warning
Enabled True
Category Assertion
Code ConstActualValueUsageAnalyzer

Description

Actual value should not be constant. This indicates that the actual and expected values have switched places.

Motivation

Bring developers' attention to a scenario in which their test is most likely testing the wrong thing, or to cases where their actual and expected values may be accidentally swapped.

How to fix violations

Example Violation

[Test]
public void Nunit2007SampleTest()
{
    var x = 5;
    Assert.That(5, Is.EqualTo(x));
    Assert.AreEqual(x, 5);
}

Explanation

Both asserts above will trigger this warning. That's because the actual value should be the value produced by your code, not a constant value that you're expecting (which should be in the place of the expected value).

In the case of equality, etc. this might seem like no big deal, but it really comes into play in the exceptions that are raised by error messages. It's important that if your test fails, the message can correctly tell you what the expected and actual values are.

As an aside, this is another reason why the Assert.That syntax is often preferred when asserting equality.

Fix

Flip the actual and expected values so that your expected value is the constant and your actual value has been generated by code.

[Test]
public void Nunit2007SampleTest()
{
    var x = 5;
    Assert.That(x, Is.EqualTo(5));
    Assert.AreEqual(5, x);
}

Configure severity

Via ruleset file.

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

Via #pragma directive.

#pragma warning disable NUnit2007 // Actual value should not be constant.
Code violating the rule here
#pragma warning restore NUnit2007 // Actual value should not be constant.

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

#pragma warning disable NUnit2007 // Actual value should not be constant.

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("Assertion", 
    "NUnit2007:Actual value should not be constant.",
    Justification = "Reason...")]
Clone this wiki locally