-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSampleIncrementalSourceGeneratorTests.cs
67 lines (54 loc) · 2.02 KB
/
SampleIncrementalSourceGeneratorTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Xunit;
namespace SourceGenerator.Tests;
public class SampleIncrementalSourceGeneratorTests
{
private const string VectorClassText = @"
namespace TestNamespace;
[Generators.Report]
public partial class Vector3
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
}";
private const string ExpectedGeneratedClassText = @"// <auto-generated/>
using System;
using System.Collections.Generic;
namespace TestNamespace;
partial class Vector3
{
public IEnumerable<string> Report()
{
yield return $""X:{this.X}"";
yield return $""Y:{this.Y}"";
yield return $""Z:{this.Z}"";
}
}
";
[Fact]
public void GenerateReportMethod()
{
// Create an instance of the source generator.
var generator = new SampleIncrementalSourceGenerator();
// Source generators should be tested using 'GeneratorDriver'.
var driver = CSharpGeneratorDriver.Create(generator);
// We need to create a compilation with the required source code.
var compilation = CSharpCompilation.Create(nameof(SampleSourceGeneratorTests),
new[] { CSharpSyntaxTree.ParseText(VectorClassText) },
new[]
{
// To support 'System.Attribute' inheritance, add reference to 'System.Private.CoreLib'.
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
});
// Run generators and retrieve all results.
var runResult = driver.RunGenerators(compilation).GetRunResult();
// All generated files can be found in 'RunResults.GeneratedTrees'.
var generatedFileSyntax = runResult.GeneratedTrees.Single(t => t.FilePath.EndsWith("Vector3.g.cs"));
// Complex generators should be tested using text comparison.
Assert.Equal(ExpectedGeneratedClassText, generatedFileSyntax.GetText().ToString(),
ignoreLineEndingDifferences: true);
}
}