Skip to content

Commit

Permalink
Fix MSTEST0017 false positive when both actual/expected are constants (
Browse files Browse the repository at this point in the history
…#4460)

Co-authored-by: Amaury Levé <amauryleve@microsoft.com>
  • Loading branch information
Youssef1313 and Evangelink authored Dec 28, 2024
1 parent a50e2b8 commit cbcc9c9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ public override void Initialize(AnalysisContext context)
});
}

private static bool IsConstant(IArgumentOperation argumentOperation)
=> argumentOperation.Value.ConstantValue.HasValue;

private static void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol assertSymbol)
{
var invocationOperation = (IInvocationOperation)context.Operation;
Expand All @@ -69,9 +72,10 @@ private static void AnalyzeOperation(OperationAnalysisContext context, INamedTyp
return;
}

// If the actual value is a constant or a literal, then the arguments are in the wrong order.
if (actualArgument.Value.Kind == OperationKind.Literal
|| actualArgument.Value.ConstantValue.HasValue)
// If the actual value is a constant or a literal and expected is not, then the arguments are in the wrong order.
// Note that we don't report if both are literals or constants, as there is no real fix for this.
// If both are literals or constants, the assert will always pass or always fail.
if (IsConstant(actualArgument) && !IsConstant(expectedArgument))
{
context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule));
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,28 @@ await VerifyCS.VerifyCodeFixAsync(
fixedCode);
}

[TestMethod]
public async Task WhenBothAreLiterals_NoDiagnostic()
{
string code = """
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
[TestClass]
public class MyTestClass
{
[TestMethod]
public void NonCompliant()
{
Assert.AreEqual(0, 0);
Assert.AreEqual(0, 1);
}
}
""";

await VerifyCS.VerifyCodeFixAsync(code, code);
}

[TestMethod]
public async Task LiteralUsingNamedArgument()
{
Expand Down

0 comments on commit cbcc9c9

Please sign in to comment.