【问题标题】:Getting the ContentRootPath or getting IHostingEnvironment in a xunit context for .NET core在 .NET 核心的 xunit 上下文中获取 ContentRootPath 或 IHostingEnvironment
【发布时间】:2016-08-12 08:56:47
【问题描述】:

我正在为 .NET 核心(net46 框架)创建 xunit 测试,但在获取应用程序的根路径时遇到问题,因此我可以找到 appsettings.json 等内容。

谁能解释我如何实现以下目标之一:

  • 获取 IHostingEnvironment 的实例

  • 获取包含xunit测试的.NET项目的绝对路径,这样我就可以自己实现IHostingEnvironment了。

这可能是一个非常简单的问题,我似乎无法找到一个好的解决方案。

【问题讨论】:

  • 您的测试项目应该有自己的 appsettings.json 版本。如果您使用的是 Microsoft.AspNetCore.TestHost.TestServer,您可以使用 var _server = new TestServer(new WebHostBuilder().UseStartup()) 之类的行,它将在您的主项目中运行启动,但使用位于在测试项目中

标签: .net-core xunit


【解决方案1】:

据我所知,在 XUnit 测试中注入 IHostingEnvironment 是不可能的。

这并不理想,但您可以这样做(例如:SetBasePath):

var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("remoteDeploymentConfig.json")
        .AddUserSecrets()
        .AddEnvironmentVariables()
        .Build();

此解决方案有效,因为如果您要执行dotnet test,您需要从项目目录本身中执行此操作,因为这里的test 对应于该项目的 xunit 包。

【讨论】:

  • 它有效,因此 Directory.GetCurrentDirectory() 似乎是我的场景的不错选择。 .
  • 在使用 resharper testrunner 运行测试用例时,这似乎不适用于 .net core 2.0-preview1。
猜你喜欢
  • 2017-05-09
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2017-04-26
  • 1970-01-01
相关资源
最近更新 更多