Skip to content

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

License

Notifications You must be signed in to change notification settings

jscarle/SourceGeneratorTestHelpers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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");
    }
}