代码之家  ›  专栏  ›  技术社区  ›  ScottishTapWater

测试生成器ExecutionContext

  •  0
  • ScottishTapWater  · 技术社区  · 2 年前

    我正在编写一个源代码生成器,作为其中的一部分,我需要阅读 .csproj 文件

    我可以使用 build_property.ProjectDir 在中 GeneratorExecutionContext.AnalyzerConfigOptions.GlobalOptions 我已经写了几个扩展方法来简化处理:

    public static class GeneratorInitializationContextExtensions
    {
        public static string GetProjectDirectory(this GeneratorExecutionContext context)
        {
            context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property.ProjectDir", out string? projectDirectory);
            if (projectDirectory is null) throw new("Can't find project directory");
            return projectDirectory;
        }
    
        public static string GetProjectFile(this GeneratorExecutionContext context)
        {
            string   projectDirectory = context.GetProjectDirectory();
            string[] files            = Directory.GetFiles(projectDirectory);
            string   projectFile      = files.Single(f => f.EndsWith(".csproj"));
            return projectFile;
        }
    }
    
    

    现在,这些工作得很好。不过,我想让他们接受一些测试。

    不幸的是,我不知道如何创建 GeneratorExecutionContext 以进行测试。它唯一的构造函数是内部的,并且 AnalyzerConfigOptionsProvider 属性没有setter。

    我该如何处理?

    0 回复  |  直到 2 年前
    推荐文章