I'm about to create tests for my Roslyn code analyzer and to its code fixer. I'm using the generated test project template that contains a lot of predefined methods to apply and verify code fixes.
However, my analyzer's code fixer would replace null
to default
. Default literal was added only in C# 7.1, but the default project that the generated test helper methods create uses C# 7.0, hence my tests always fail. I don't want to change my analyzer to use default(<type>)
(actually there are cases when the type is unknown to the analyzer).
This is how the generated method creates a new workspace with a project:
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, TestProjectName, TestProjectName, language)
.AddMetadataReference(projectId, CorlibReference)
.AddMetadataReference(projectId, SystemCoreReference)
.AddMetadataReference(projectId, CSharpSymbolsReference)
.AddMetadataReference(projectId, CodeAnalysisReference);
I can't figure out how would I able to specify the .NET target framework version there. In a .csproj file, we add this tag:
<TargetFramework>net472</TargetFramework>
How to do the same with Roslyn Code Analyzers?
You need to add custom parse options to choose a different language version. WithProjectParseOptions
should do what you want.
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, TestProjectName, TestProjectName, language)
.AddMetadataReference(projectId, CorlibReference)
.AddMetadataReference(projectId, SystemCoreReference)
.AddMetadataReference(projectId, CSharpSymbolsReference)
.AddMetadataReference(projectId, CodeAnalysisReference)
.WithProjectParseOptions(projectId, new CSharpParseOptions(LanguageVersion.CSharp7_1));