Last active
November 19, 2022 10:03
-
-
Save chsienki/2955ed9336d7eb22bcb246840bfeb05c to your computer and use it in GitHub Desktop.
Framework for unit testing generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp; | |
using System.Collections.Immutable; | |
using System.Linq; | |
using System.Reflection; | |
using Xunit; | |
namespace GeneratorTests.Tests | |
{ | |
public class GeneratorTests | |
{ | |
[Fact] | |
public void SimpleGeneratorTest() | |
{ | |
string userSource = @" | |
namespace MyCode | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
} | |
} | |
} | |
"; | |
Compilation comp = CreateCompilation(userSource); | |
var newComp = RunGenerators(comp, out var generatorDiags, new SimpleGenerator()); | |
Assert.Empty(generatorDiags); | |
Assert.Empty(newComp.GetDiagnostics()); | |
} | |
private static Compilation CreateCompilation(string source) | |
=> CSharpCompilation.Create("compilation", | |
new[] { CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.Preview)) }, | |
new[] { MetadataReference.CreateFromFile(typeof(Binder).GetTypeInfo().Assembly.Location) }, | |
new CSharpCompilationOptions(OutputKind.ConsoleApplication)); | |
private static GeneratorDriver CreateDriver(Compilation c, params ISourceGenerator[] generators) | |
=> new CSharpGeneratorDriver(c.SyntaxTrees.First().Options, | |
ImmutableArray.Create(generators), | |
null, | |
ImmutableArray<AdditionalText>.Empty); | |
private static Compilation RunGenerators(Compilation c, out ImmutableArray<Diagnostic> diagnostics, params ISourceGenerator[] generators) | |
{ | |
CreateDriver(c, generators).RunGeneratorsAndUpdateCompilation(c, out var d, out diagnostics); | |
return d; | |
} | |
} | |
} |
@sharwell Does the testing library supports passing
.editorconfig
for generators? (it does for analyzers & codefixes, but not sure about generators)
Yes, you can add them to TestState.AnalyzerConfigFiles
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sharwell Does the testing library supports passing
.editorconfig
for generators? (it does for analyzers & codefixes, but not sure about generators)