diff --git a/src/xunit.analyzers.tests/Analyzers/X1000/UseCancellationTokenTests.cs b/src/xunit.analyzers.tests/Analyzers/X1000/UseCancellationTokenTests.cs index 6992f5bd..7e1b2cb2 100644 --- a/src/xunit.analyzers.tests/Analyzers/X1000/UseCancellationTokenTests.cs +++ b/src/xunit.analyzers.tests/Analyzers/X1000/UseCancellationTokenTests.cs @@ -53,9 +53,13 @@ public async Task WithAnyCancellationToken_DoesNotTrigger(string token) class TestClass {{ [Fact] - public async Task TestMethod() {{ - await Task.Delay(1, {0}); + public void TestMethod() {{ + FunctionWithDefaults(42, {0}); + FunctionWithDefaults(42, cancellationToken: {0}); + FunctionWithDefaults(cancellationToken: {0}); }} + + void FunctionWithDefaults(int _1 = 2112, CancellationToken cancellationToken = default(CancellationToken)) {{ }} }} """, token); diff --git a/src/xunit.analyzers/X1000/UseCancellationToken.cs b/src/xunit.analyzers/X1000/UseCancellationToken.cs index 42a8cb6e..0519bd3e 100644 --- a/src/xunit.analyzers/X1000/UseCancellationToken.cs +++ b/src/xunit.analyzers/X1000/UseCancellationToken.cs @@ -36,16 +36,17 @@ public override void AnalyzeCompilation( var invokedMethod = invocationOperation.TargetMethod; var parameters = invokedMethod.Parameters; - var parameterIdx = 0; - for (; parameterIdx < parameters.Length; ++parameterIdx) - if (SymbolEqualityComparer.Default.Equals(parameters[parameterIdx].Type, cancellationTokenType)) + IArgumentOperation? argument = null; + foreach (var parameter in parameters) + if (SymbolEqualityComparer.Default.Equals(parameter.Type, cancellationTokenType)) + { + argument = invocationOperation.Arguments.FirstOrDefault(arg => SymbolEqualityComparer.Default.Equals(arg.Parameter, parameter)); break; + } // The invoked method has the parameter we're looking for - if (parameterIdx != parameters.Length) + if (argument is not null) { - var argument = invocationOperation.Arguments[parameterIdx]; - // Default parameter value if (argument.ArgumentKind == ArgumentKind.DefaultValue) Report(context, invocationOperation.Syntax.GetLocation()); @@ -61,7 +62,7 @@ public override void AnalyzeCompilation( // Look for an overload with the exact same parameter types + a CancellationToken else { - var targetParameterTypes = invokedMethod.Parameters.Select(p => p.Type).Concat([cancellationTokenType]).ToArray(); + var targetParameterTypes = parameters.Select(p => p.Type).Concat([cancellationTokenType]).ToArray(); foreach (var member in invokedMethod.ContainingType.GetMembers(invokedMethod.Name)) if (member is IMethodSymbol method) {