Source Generator Testing

593 views Asked by At

I'm trying to develop a source generator that I can theoretically add to my projects, and for the given project have it find classes that are marked up with a specific attribute, and then build a corresponding generated file for each.

I've set up unit tests that effectively use GeneratorDriver to instantiate and run generators and evaluate their output.

Problem

Classes exist in a secondary project referenced from the test project. The compilation does not appear to include syntaxTree's for the other project.

I've tried calling CreateCompilation with a simple program.cs body, and calling .AddReferences(MetadataReference.CreateFromFile(typeof(User).Assembly.Location), and then passing that to the in driver.

At runtime, my syntax trees are still all the same (perhaps because I assume that reference is treated like an assembly reference.

I assume in normal situations, generators will run with the context of projects they are referenced from as an Analyzer, but for the purposes of my unit testing, is there a way I can effectively set the compilation to be another project, or reference another project (such that when I walk the different syntax trees, I can access those classes marked with attributes in an external assembly)?

1

There are 1 answers

2
Ronnyek On

So I managed to get this fixed by creating a workspace (with Microsoft.CodeAnalysis.Workspaces) and loaded my other project in, got the compilation from that, and passed that to my GeneratorDriver.

My Generator isn't working 100% yet, but this definitely got me past the hurdle.