我能够分别找到测试分析器和源生成器的所有示例。但我的分析器坚持使用源生成器生成的属性。如何在单次测试运行中结合源代码生成器和语法分析器?
只需在编译上运行生成器,然后使用
WithAnalyzers
附加分析器 - 请参阅我对此任务的看法here(预增量生成器,因此可能会出现一些复杂情况),这可以在以下基础中进行一些总结用于测试的类(与存储库相比删除了一些代码):
public abstract class GeneratorWithAnalyzerTestBase
{
protected Task<ImmutableArray<Diagnostic>> RunAnalyzer<T>(T analyzer, Compilation compilation)
where T : DiagnosticAnalyzer
{
var compilationWithAnalyzers =
// run generators on the compilation
RunGenerators(compilation, out _, new SomeGenerator())
// attach analyzers
.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer));
// collect diagnostics
return compilationWithAnalyzers.GetAllDiagnosticsAsync();
}
protected Compilation RunGenerators(Compilation compilation,
out ImmutableArray<Diagnostic> diagnostics,
params ISourceGenerator[] generators)
{
CreateDriver(compilation, generators)
.RunGeneratorsAndUpdateCompilation(compilation, out var updatedCompilation, out diagnostics);
return updatedCompilation;
}
protected GeneratorDriver CreateDriver(Compilation compilation, params ISourceGenerator[] generators) =>
CSharpGeneratorDriver.Create(
ImmutableArray.Create(generators),
ImmutableArray<AdditionalText>.Empty,
(CSharpParseOptions)compilation.SyntaxTrees.First().Options
);
}