Test helpers and extension methods to simplify testing of .NET source generators.
var (generator, result) = SourceGenerator.Run<YourSourceGenerator>("your source");You can also run a generator against multiple source files by passing any IEnumerable<string>.
var sources = new[]
{
"namespace Tests; public partial class First;",
"namespace Tests; public partial class Second;"
};
var (generator, result) = SourceGenerator.Run<YourSourceGenerator>(sources);var (generator, result) = IncrementalGenerator.Run<YourSourceGenerator>("your source");The same multiple-source overload is available for incremental generators.
var sources = new[]
{
"namespace Tests; public partial class First;",
"namespace Tests; public partial class Second;"
};
var (generator, result) = IncrementalGenerator.Run<YourSourceGenerator>(sources);var generatedSources = result.GetSources();var generatedSource = result.GetSource("TestId.g.cs");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);Using one of the testing framework packages below, you can also assert the difference between the generated source and the expected source.
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);Support for Verify is built-in using the VerifyAsync method.
Generated source text is normalized to LF line endings before it is passed to Verify.
public class SourceGeneratorTests
{
[Fact]
public Task ShouldProductTestId()
{
var (_, result) = IncrementalGenerator.Run<YourSourceGenerator>("your source");
return result.VerifyAsync("TestId.g.cs");
}
}For parameterized tests, pass a stable snapshot name to avoid framework-specific parameter text in the snapshot file name:
return result.VerifyAsync("TestId.g.cs", snapshotName: "SourceGeneratorTests.ShouldProduceTestId");[TestFixture]
public class SourceGeneratorTests
{
[Test]
public Task ShouldProductTestId()
{
var (_, result) = IncrementalGenerator.Run<YourSourceGenerator>("your source");
return result.VerifyAsync("TestId.g.cs");
}
}[TestClass]
public class SourceGeneratorTests :
GeneratorDriverTestBase
{
[TestMethod]
public Task ShouldProductTestId()
{
var (_, result) = IncrementalGenerator.Run<YourSourceGenerator>("your source");
return VerifyAsync(result, "TestId.g.cs");
}
}