Extends Verify to allow verification of C# Source Generators.
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 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
[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 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),
Description: ,
HelpLink: ,
MessageFormat: the message from {0},
Message: the message from hello world generator,
Category: the category,
CustomTags: []
}
]
}
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.