Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
MSTEST0065: Avoid
| Property | Value |
|---|---|
| Rule ID | MSTEST0065 |
| Title | Avoid Assert.AreEqual on collection types |
| Category | Usage |
| Fix is breaking or non-breaking | Non-breaking |
| Enabled by default | Yes |
| Default severity | Warning |
| Introduced in version | 4.3.0 |
| Is there a code fix | No |
Note
This rule is available starting with MSTest 4.3.
Cause
A call to Assert.AreEqual or Assert.AreNotEqual is made on a value whose static type implements IEnumerable<T> (other than String).
Rule description
AreEqual and AreNotEqual use EqualityComparer<T>.Default. For most collection types — for example arrays, List<T>, or any user-defined type implementing IEnumerable<T> — this falls back to reference equality (or to whatever equality the type defines for itself), and not to element-wise comparison. As a result, the assertion almost never asserts what the test author intended.
[TestClass]
public class TestClass
{
[TestMethod]
public void Test()
{
var expected = new[] { 1, 2, 3 };
var actual = new[] { 1, 2, 3 };
// Violation: this compares references, not contents, and fails.
Assert.AreEqual(expected, actual);
}
}
How to fix violations
Choose the assertion that matches your intent:
- Use
Assert.AreSequenceEqualfor ordered element-wise comparison. - Use
Assert.AreSequenceEqual(expected, actual, SequenceOrder.InAnyOrder)for unordered element-wise comparison. - Use
Assert.AreEquivalentfor deep structural comparison.
[TestClass]
public class TestClass
{
[TestMethod]
public void Test()
{
var expected = new[] { 1, 2, 3 };
var actual = new[] { 1, 2, 3 };
Assert.AreSequenceEqual(expected, actual);
}
}
When to suppress warnings
Suppress this warning only if the type defines its own Equals/GetHashCode to compare contents and you intentionally rely on that.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable MSTEST0065
// The code that's violating the rule is on this line.
#pragma warning restore MSTEST0065
To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.MSTEST0065.severity = none
For more information, see How to suppress code analysis warnings.