dotnet/roslyn-sdk

Consider marking AnalyzerTest `TestCode` as virtual to allow for test-code syntax highlighting in Visual Studio

JakeYallop opened this issue · 0 comments

Description

I was recently made aware of this nifty feature, that Visual Studio can syntax highlight your embedded C# code:
image.

However, currently this requires tests to be written a certain way. For most cases, creating a method is sufficient: e.g

https://github.com/dotnet/roslyn/blob/5eae7ca4f42121aabc4456cebc0400cd160d73f7/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier%601.cs#L17-L19

However, for existing tests that are not written in this way, it would time consuming to change this. For example, many of the tests in the Roslyn repository are written like so:

https://github.com/dotnet/roslyn/blob/5eae7ca4f42121aabc4456cebc0400cd160d73f7/src/Analyzers/CSharp/Tests/UseCollectionExpression/UseCollectionExpressionForArrayTests.cs#L24-L35

As the TestCode property is not language-specific, there is no specific attribute that can be added directly to the property itself in the package, however, if a consumer had the ability to override the TestCode property, they could add the pre-requisite attribute themselves for their language-specific test analyzer.

For example

public static partial class CSharpCodeFixVerifier<TAnalyzer, TCodeFix>
    where TAnalyzer : DiagnosticAnalyzer, new()
    where TCodeFix : CodeFixProvider, new()
{

  [StringSyntax("C#-test")]
  public override string TestCode
  {
      set
      {
          if (value != null)
          {
              TestState.Sources.Add(value);
          }
      }
  }
}

Risks

According to dotnet/runtime#21750, marking a member as virtual is a breaking change. Assuming this piece of knowledge is still relevant, in this the normal pattern of using the property makes it highly unlikely that such a break would occur.