Extends Verify to allow verification of C# Source Generators.
Part of the .NET Foundation
https://nuget.org/packages/Verify.SourceGenerators/
Install one of the Verify testing framework adapters NuGet packages.
Call VerifySourceGenerators.Enable()
once at assembly load time.
using System.Runtime.CompilerServices;
using VerifyTests;
public static class ModuleInitializer
{
[ModuleInitializer]
public static void Init()
{
VerifySourceGenerators.Enable();
}
}
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 message from {0}",
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, "hello world generator");
context.ReportDiagnostic(diagnostic);
}
public void Initialize(GeneratorInitializationContext context)
{
}
}
Can be tested as follows:
This snippets assumes use of the XUnit Verify adapter, change the using VerifyXUnit
if using other testing frameworks.
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 message from {0},
Message: the message from hello world generator,
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.