【问题标题】:how to get the path of the StartUp project in Unit Test project?如何在单元测试项目中获取启动项目的路径?
【发布时间】:2019-09-09 08:53:01
【问题描述】:

我正在使用NUnit 编写单元测试。这是我的被测类的样子

public class CustomerService
{
 private readonly IConfiguration _configuration;

 // ctor
 CustomerService(IConfiguration configuration)
 {
 }
}

上述类的单元测试。

public class CustomerServiceTests
{
   private readonly IConfiguration _configuration;

   CustomerServiceTests()
   {
      _configuration =  GetConfiguration();
   }

   public static IConfiguration GetConfiguration(string outputPath="")
    {
        return new ConfigurationBuilder()
                .SetBasePath(outputPath)
                .AddJsonFile("appsettings.json", optional: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                .Build();
    }

}

现在我需要获取 StartUp (API) 项目中存在的 appsettings.json 目录的路径

这是我的项目目录的样子

  • 客户项目

    -customer.api

    -customer.services

    -customer.services.test

如何获取包含appsettings.jsoncustomer.api 项目的路径?

【问题讨论】:

  • 您的代码刚刚使用SetBasePath 指定了该路径。 CustomerServiceTests 甚至不会编译,因为 GetConfiguration 期望 outputPath 丢失
  • @PanagiotisKanavos 对不起!我没找到你
  • 您要查找的基本路径是 outputPath,您刚刚在 SetBasePath(outputPath) 调用中指定了它。

标签: c# asp.net-core dependency-injection nunit filepath


【解决方案1】:

你可以这样做:

public static string GetProjectPath(Type startupClass)
{
    var assembly = startupClass.GetTypeInfo().Assembly;
    var projectName = assembly.GetName().Name;
    var applicationBasePath = AppContext.BaseDirectory;
    var directoryInfo = new DirectoryInfo(applicationBasePath);
    do
    {
       directoryInfo = directoryInfo.Parent;

       var projectDirectoryInfo = new DirectoryInfo(directoryInfo.FullName);
       if (projectDirectoryInfo.Exists)
       {
          var projectFileInfo = new FileInfo(Path.Combine(projectDirectoryInfo.FullName, projectName, $"{projectName}.csproj"));
          if (projectFileInfo.Exists)
          {  
              return Path.Combine(projectDirectoryInfo.FullName, projectName);
          }
       }
    } while (directoryInfo.Parent != null);
}

这样称呼:

var path = GetProjectPath(typeof(StartUp));

【讨论】:

  • 这个方法怎么调用
  • @Kgn-web 添加了一个示例调用。
【解决方案2】:

您可以通过遵循 IOptions 模式来帮自己一个大忙,而不是将 IConfiguration 注入控制器。然后,您可以轻松地在单元测试中模拟出要传递给控制器​​的配置,而无需与您的 appsettings 进行集成测试。

Options pattern in ASP.NET Core

还有很多关于如何在单元测试中设置 IOptions 的示例,例如 Here

一般来说,如果您的单元测试需要依赖于被测单元的某个次要工件,那么您是在进行集成测试而不是单元测试。这些测试往往很难保持写入。

【讨论】:

    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 2014-11-20
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多