Skip to content

Commit 78b1b3b

Browse files
authored
Fix MSTEST0017 false positive when both actual/expected are constants (#4460) (#4510)
1 parent 0a38c6c commit 78b1b3b

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/Analyzers/MSTest.Analyzers/AssertionArgsShouldBePassedInCorrectOrderAnalyzer.cs

+7-3
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ public override void Initialize(AnalysisContext context)
5757
});
5858
}
5959

60+
private static bool IsConstant(IArgumentOperation argumentOperation)
61+
=> argumentOperation.Value.ConstantValue.HasValue;
62+
6063
private static void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol assertSymbol)
6164
{
6265
var invocationOperation = (IInvocationOperation)context.Operation;
@@ -69,9 +72,10 @@ private static void AnalyzeOperation(OperationAnalysisContext context, INamedTyp
6972
return;
7073
}
7174

72-
// If the actual value is a constant or a literal, then the arguments are in the wrong order.
73-
if (actualArgument.Value.Kind == OperationKind.Literal
74-
|| actualArgument.Value.ConstantValue.HasValue)
75+
// If the actual value is a constant or a literal and expected is not, then the arguments are in the wrong order.
76+
// Note that we don't report if both are literals or constants, as there is no real fix for this.
77+
// If both are literals or constants, the assert will always pass or always fail.
78+
if (IsConstant(actualArgument) && !IsConstant(expectedArgument))
7579
{
7680
context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule));
7781
return;

test/UnitTests/MSTest.Analyzers.UnitTests/AssertionArgsShouldBePassedInCorrectOrderAnalyzerTests.cs

+21
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,27 @@ await VerifyCS.VerifyCodeFixAsync(
161161
fixedCode);
162162
}
163163

164+
public async Task WhenBothAreLiterals_NoDiagnostic()
165+
{
166+
string code = """
167+
using Microsoft.VisualStudio.TestTools.UnitTesting;
168+
using System.Collections.Generic;
169+
170+
[TestClass]
171+
public class MyTestClass
172+
{
173+
[TestMethod]
174+
public void NonCompliant()
175+
{
176+
Assert.AreEqual(0, 0);
177+
Assert.AreEqual(0, 1);
178+
}
179+
}
180+
""";
181+
182+
await VerifyCS.VerifyCodeFixAsync(code, code);
183+
}
184+
164185
public async Task LiteralUsingNamedArgument()
165186
{
166187
string code = """

0 commit comments

Comments
 (0)