Skip to content

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

Description

@bdovaz

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.

TestState = new SolutionState(DefaultTestProjectName, Language, DefaultFilePathPrefix, DefaultFileExt);

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);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions