Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
bdovaz opened this issue Mar 6, 2025 · 0 comments

Comments

@bdovaz
Copy link

bdovaz commented Mar 6, 2025

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);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant