在为我的ASPNet.Core Web应用程序构建集成测试时,我遇到了一个问题。当我运行应用程序并读取配置时,其中包含了我
现在,如何将新的配置注入到启动项中?我们的启动项定义如下:
根据 @poke 的上一篇帖子进行修改
apsettings.json
文件中的所有信息。现在,当我按照下面所示运行集成测试时,启动程序被运行,但是配置不同。为什么会发生这种情况,我该如何确保它读取应用程序本身的配置?参考链接:https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing
[TestFixture]
class HSMControllerTests
{
private readonly TestServer _server;
private readonly HttpClient _client;
public HSMControllerTests()
{
_server = new TestServer(new WebHostBuilder()
.UseStartup<Startup>());
_client = _server.CreateClient();
}
[Test]
public async global::System.Threading.Tasks.Task GET_PingHSM_ShouldSucceedAsync()
{
HttpResponseMessage response = await _client.GetAsync("HSM/PingHSM");
Assert.NotNull(response);
Assert.IsInstanceOf<OkObjectResult>(response);
}
}
我遇到了一个异常:缺少配置节ServiceConfig。
这是在我的应用程序中 Program.cs
中构建 WebHost 的方式:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(o => o.AddServerHeader = false)
.Build();
可能是测试代码中构建方式的差异导致的问题吗?
修改后的ControllerTest构造函数:
public HSMControllerTests()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Path.GetFullPath(@"../../../../HSM.WebApi.IntegrationTests"))
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
_server = new TestServer(WebHost.CreateDefaultBuilder()
.UseStartup<Startup>());
_client = _server.CreateClient();
}
现在,如何将新的配置注入到启动项中?我们的启动项定义如下:
public Startup(IConfiguration configuration, IHostingEnvironment environment)
: base(typeof(Startup), configuration, environment)
{
}
根据 @poke 的上一篇帖子进行修改
_server = new TestServer(WebHost.CreateDefaultBuilder()
.ConfigureAppConfiguration(configBuilder => new ConfigurationBuilder()
.SetBasePath(Path.GetFullPath(@"../../../../HSM.WebApi.IntegrationTests"))
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
)
.UseStartup<Startup>());
搞定了,有些问题还需要解决...
var config = new ConfigurationBuilder()
.SetBasePath(Path.GetFullPath(@"../../../../HSM.WebApi.IntegrationTests"))
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
var Configuration = config.Build();
_server = new TestServer(WebHost.CreateDefaultBuilder()
.UseConfiguration(Configuration)
.UseStartup<Startup>());
_client = _server.CreateClient();
但是现在,HostingEnvironment被设置为Tests应用程序的目录,而不是Web应用程序的目录,并且它试图从HomeController构造函数中的那里读取appsettings.json
文件,位置如下:
public HSMController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
contentRootPath = _hostingEnvironment.ContentRootPath;
}
IWebHostBuilder.ConfigureAppConfiguration
,例如new WebHostBuilder().ConfigureAppConfiguration(configBuilder => configBuilder.SetBasePath(…).AddJsonFile(…)).UseStartup<Startup>())
。 - poke