jscarle / SourceGeneratorTestHelpers

Test helpers and extension methods to simplify testing of .NET source generators.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Source Generator Test Helpers

Test helpers and extension methods to simplify testing of .NET source generators.

main nuget downloads

Testing a source generator

var result = SourceGenerator.Run<YourSourceGenerator>("your source");

Testing an incremental source generator

var result = IncrementalGenerator.Run<YourSourceGenerator>("your source");

Obtaining the generated source

Getting all generated sources

var generatedSources =  result.GetSources();

A single source that ends with a specific file path

var generatedSource =  result.GetSource("TestId.g.cs");

Compare the generated source with the expected source

You can produce a diff between the generated source and the expected source. The result will contain a boolean hasDifferences and a line by line diff in differences.

var (hasDifferences, differences) = Diff.Compare(generatedSource, expectedSource);

Assert the difference

Using one of the testing framework packages below, you can also assert the difference between the generated source and the expected source.

XUnit NUnit MSTest

var result = IncrementalGenerator.Run<YourSourceGenerator>("your source");

result.ShouldProduce("TestId.g.cs", "expected source");

Note: If you do not wish to assert on errors produced during diagnostics of the source generator run, you can simply disable them as such.

var result = IncrementalGenerator.Run<YourSourceGenerator>("your source");

result.ShouldProduce("TestId.g.cs", "expected source", false);

Verify the difference

Support for Verify is built-in using the VerifyAsync method.

XUnit

public class SourceGeneratorTests
{
    [Fact]
    public Task ShouldProductTestId()
    {
        var result = IncrementalGenerator.Run<YourSourceGenerator>("your source");
        return result.VerifyAsync("TestId.g.cs");
    }
}

NUnit

[TestFixture]
public class SourceGeneratorTests
{
    [Test]
    public Task ShouldProductTestId()
    {
        var result = IncrementalGenerator.Run<YourSourceGenerator>("your source");
        return result.VerifyAsync("TestId.g.cs");
    }
}

MSTest

[TestClass]
public class SourceGeneratorTests :
    GeneratorDriverTestBase
{
    [TestMethod]
    public Task ShouldProductTestId()
    {
        var result = IncrementalGenerator.Run<YourSourceGenerator>("your source");
        return VerifyAsync("TestId.g.cs");
    }
}

About

Test helpers and extension methods to simplify testing of .NET source generators.

License:MIT License


Languages

Language:C# 100.0%