roslyn-sdk icon indicating copy to clipboard operation
roslyn-sdk copied to clipboard

It is not possible to override DefaultFilePathPrefix and DefaultTestProjectName properties of the AnalyzerTest class

Open bdovaz opened this issue 7 months ago • 0 comments

Those 2 variables are virtual but they are called in the constructor so the behavior is not as expected. That is, it will use the default value because the override is evaluated after the constructor of the base class.

https://github.com/dotnet/roslyn-sdk/blob/102440e23287dd5b5f4598f00fd74aeef8c7b555/src/Microsoft.CodeAnalysis.Testing/Microsoft.CodeAnalysis.Analyzer.Testing/AnalyzerTest%601.cs#L67

Explanation: https://rules.sonarsource.com/csharp/RSPEC-1699/

To solve the particular case I needed, which is the project name temporarily, I had to use reflection...

private class CSharpAnalyzerTestWithProjectName<TAnalyzer, TVerifier> : CSharpAnalyzerTest<TAnalyzer, TVerifier>
    where TAnalyzer : DiagnosticAnalyzer, new ()
    where TVerifier : IVerifier, new ()
{
    private readonly string _projectName;

    protected override string DefaultTestProjectName => _projectName;

    public CSharpAnalyzerTestWithProjectName(string projectName)
    {
        _projectName = projectName;

        FieldInfo nameField = typeof(ProjectState).GetField("<Name>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic)!;
        nameField.SetValue(TestState, _projectName);
    }
}

bdovaz avatar Mar 06 '25 09:03 bdovaz