Skip to content

Commit a9232d8

Browse files
authored
Merge pull request #906 from nunit/Issue896_typeof_generic
Don't treat typeof(T) as a constant as it depends on parameters.
2 parents 0965208 + 2b0ae04 commit a9232d8

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

src/nunit.analyzers.tests/ConstActualValueUsage/ConstActualValueUsageAnalyzerTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -481,5 +481,27 @@ public void Test()
481481

482482
RoslynAssert.Diagnostics(analyzer, expectedDiagnostic, testCode);
483483
}
484+
485+
[Test]
486+
public void TypeOfGenericIsNotAConstant()
487+
{
488+
var testCode = TestUtility.WrapClassInNamespaceAndAddUsing("""
489+
public class MyExplicitlyTypedTests
490+
{
491+
[TestCaseSource(nameof(ExplicitTypeArgsTestCases))]
492+
public void ExplicitTypeArgs<T>(T input)
493+
{
494+
Assert.That(typeof(T), Is.EqualTo(typeof(long)));
495+
}
496+
497+
private static IEnumerable<TestCaseData> ExplicitTypeArgsTestCases()
498+
{
499+
yield return new TestCaseData(2);
500+
yield return new TestCaseData(2L);
501+
}
502+
}
503+
""", "using System.Collections.Generic;");
504+
RoslynAssert.Valid(analyzer, testCode);
505+
}
484506
}
485507
}

src/nunit.analyzers/ConstActualValueUsage/ConstActualValueUsageAnalyzer.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,13 @@ void Report(IOperation operation)
6262
return;
6363
}
6464

65+
if (actualOperation is ITypeOfOperation typeOfOperation &&
66+
typeOfOperation.TypeOperand.Kind == SymbolKind.TypeParameter)
67+
{
68+
// typeof(T) is a special case, it is not a constant value as it depends on the parameter.
69+
return;
70+
}
71+
6572
// The actual expression is a constant field, check if expected is also constant
6673
var expectedOperation = GetExpectedOperation(assertOperation);
6774

0 commit comments

Comments
 (0)