Unit testing: how to validate code that is fed to source generator? #75083
-
Hello I'm using Is there a way to validate that the inputs of the generator are valid and can be compiled before running generator in the context of a unit test? I'm running the generator as follows: private static GeneratorDriverRunResult RunGenerators(params string[] sources)
{
var compilation = CSharpCompilation.Create(
nameof(CodeGeneratorTests),
sources.Select(text => CSharpSyntaxTree.ParseText(text)),
[
// To support 'System.Attribute' inheritance, add reference to 'System.Private.CoreLib'.
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
]);
return CSharpGeneratorDriver
.Create(new MyCodeGenerator())
.RunGenerators(compilation)
.GetRunResult();
} I'm just starting my journey with source generators, help is appreciated! If it's covered or was discussed, will appreciate a link or reference... Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
You'll have to ask on the Verify repo. This is a common complaint I hear from users of this testing library, and it's worth raising with them. The official testing SDK verifies that diagnostics are either not present or match a list of expected diagnostics, which prevents this issue. |
Beta Was this translation helpful? Give feedback.
These diagnostics are only diagnostics that are raised by generators that are run, ie things produced by output sources that raise diagnostics. If you want to get all diagnostics from the entire compilation, then you need to save the compilation, rather than discarding it, and get all diagnostics from it.
/cc @chsienki, it looks like we don't have documentation on that API, and this is a pitfall I've seen before. We should document this better.