org.sonar.plugins.csharp.S2701.html Maven / Gradle / Ivy
Why is this an issue?
Using literal boolean values in assertions can lead to less readable and less informative unit tests. When a test fails, it’s important to have a
clear understanding of what the test was checking and why it failed. Most of the testing frameworks provide more explicit assertion methods that will
provide a more helpful error message if the test fails.
Exceptions
In the context of xUnit, Assert.True
and Assert.False
are not flagged by this rule. This is because
Assert.Fail
was only introduced in 2020 with version 2.4.2
. Prior to this, developers used Assert.True(false,
message)
and Assert.False(true, message)
as workarounds to simulate the functionality of Assert.Fail()
.
How to fix it in MSTest
Code examples
Noncompliant code example
bool someResult;
Assert.AreEqual(false, someResult); // Noncompliant: use Assert.IsFalse
Assert.AreEqual(true, someResult); // Noncompliant: use Assert.IsTrue
Assert.AreNotEqual(false, someResult); // Noncompliant: use Assert.IsTrue
Assert.AreNotEqual(true, someResult); // Noncompliant: use Assert.IsFalse
Assert.IsFalse(true, "Should not reach this line!"); // Noncompliant: use Assert.Fail
Assert.IsTrue(false, "Should not reach this line!"); // Noncompliant: use Assert.Fail
Assert.IsFalse(false); // Noncompliant: remove it
Compliant solution
bool someResult;
Assert.IsFalse(someResult);
Assert.IsTrue(someResult);
Assert.IsTrue(someResult);
Assert.IsFalse(someResult);
Assert.Fail("Should not reach this line!");
Assert.Fail("Should not reach this line!");
// Removed
How to fix it in NUnit
Code examples
Noncompliant code example
bool someResult;
Assert.AreEqual(false, someResult); // Noncompliant: use Assert.False
Assert.AreEqual(true, someResult); // Noncompliant: use Assert.True
Assert.AreNotEqual(false, someResult); // Noncompliant: use Assert.True
Assert.AreNotEqual(true, someResult); // Noncompliant: use Assert.False
Assert.False(true, "Should not reach this line!"); // Noncompliant: use Assert.Fail
Assert.True(false, "Should not reach this line!"); // Noncompliant: use Assert.Fail
Assert.False(false); // Noncompliant: remove it
Compliant solution
bool someResult;
Assert.False(someResult);
Assert.True(someResult);
Assert.True(someResult);
Assert.False(someResult);
Assert.Fail("Should not reach this line!");
Assert.Fail("Should not reach this line!");
// Removed
How to fix it in xUnit
Code examples
Noncompliant code example
bool someResult;
Assert.Equal(false, someResult); // Noncompliant: use Assert.False
Assert.Equal(true, someResult); // Noncompliant: use Assert.True
Assert.NotEqual(false, someResult); // Noncompliant: use Assert.True
Assert.NotEqual(true, someResult); // Noncompliant: use Assert.False
Compliant solution
bool someResult;
Assert.False(someResult);
Assert.True(someResult);
Assert.True(someResult);
Assert.False(someResult);
Resources
Documentation
© 2015 - 2024 Weber Informatics LLC | Privacy Policy