Extends Verify to allow verification of C# Source Generators.
Part of the .NET Foundation
https://nuget.org/packages/Verify.SourceGenerators/
Call VerifySourceGenerators.Enable()
once at assembly load time.
Given a Source Generator:
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
[Generator]
public class HelloWorldGenerator :
ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
var source = @"using System;
public static class HelloWorld
{
public static void SayHello()
{
Console.WriteLine(""Hello from generated code!"");
}
}";
context.AddSource("helloWorldGenerator", SourceText.From(source, Encoding.UTF8));
var descriptor = new DiagnosticDescriptor(
id: "theId",
title: "the title",
messageFormat: "the descriptor",
category: "the category",
DiagnosticSeverity.Info,
isEnabledByDefault: true);
var location = Location.Create(
"theFile",
new TextSpan(1, 2),
new LinePositionSpan(
new LinePosition(1, 2),
new LinePosition(3, 4)));
var diagnostic = Diagnostic.Create(descriptor, location);
context.ReportDiagnostic(diagnostic);
}
public void Initialize(GeneratorInitializationContext context)
{
}
}
Can be tested as follows:
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using VerifyXunit;
using Xunit;
[UsesVerify]
public class SampleTest
{
[Fact]
public Task Run()
{
var compilation = CSharpCompilation.Create("name");
HelloWorldGenerator generator = new();
GeneratorDriver driver = CSharpGeneratorDriver.Create(generator);
driver = driver.RunGenerators(compilation);
return Verifier.Verify(driver);
}
}
And will result in the following verified files:
An info file containing all metadata about the current state. eg any Diagnostics.
{
Diagnostics: [
{
Id: theId,
Title: the title,
Severity: Info,
WarningLevel: 1,
Location: theFile: (1,2)-(3,4),
MessageFormat: the descriptor,
Category: the category
}
]
}
Multiple source files. One for each GeneratorDriverRunResult.Results.GeneratedSources
.
//HintName: helloWorldGenerator.cs
using System;
public static class HelloWorld
{
public static void SayHello()
{
Console.WriteLine("Hello from generated code!");
}
}
Sauce designed by April Hsuan from The Noun Project.