Skip to content

MSTEST0017: false positive with user-defined conversion operators #7578

@Zastai

Description

@Zastai

Describe the bug

A test method uses Assert.Equals() where the expected value is an expression, and the actual value is a constant to which a user-defined conversion operator is applied.

This should be fine usage - both sides involve user code, so there is no reason to consider the parameters inverted.

Version used

4.1.0

Steps To Reproduce

Use the following test class:

[TestClass]
public class FalsePositiveForMsTest0017 {

  private sealed class Foo(string s) : IEquatable<Foo> {

    private readonly string TheString = s;

    public static explicit operator Foo(string s) => new(s);

    public override bool Equals(object? obj) => this.Equals(obj as Foo);

    public bool Equals(Foo? other) => other is not null && this.TheString.Equals(other.TheString);

    public override int GetHashCode() => HashCode.Combine(this.TheString);

  }

  [TestMethod]
  public void ConversionOperatorHasSameResultAsConstructor()
    => Assert.AreEqual(new Foo("Hello"), (Foo) "Hello");

}

Expected behavior

No analyzer warning reported for the test method.

Actual behavior

MSTEST0017: Assertion arguments should be passed in the correct order. 'actual' and 'expected'/'notExpected' arguments have been swapped.

Swapping the parameters makes the diagnostic go away, but is not really correct, given the test is supposed to be testing the conversion operator.

Metadata

Metadata

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions