我使用Asp Net Core制作的Web应用程序,我尝试使用TestServer进行集成测试 .
我按照这个blog post来设置我的测试环境 .
应用程序的Startup.cs如下所示:
public class Startup
{
public Startup(IHostingEnvironment env)
{
applicationPath = env.WebRootPath;
contentRootPath = env.ContentRootPath;
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(contentRootPath)
.AddJsonFile("appsettings.json")
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
// Many services are called here
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
// Many config are made here
loggerFactory.AddSerilog();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=auth}/{action=login}/{id?}");
});
}
}
对于集成测试,我使用此代码创建WebHostBuilder
var builder = new WebHostBuilder()
.UseContentRoot(appRootPath)
.UseStartup<TStartup>()
.UseEnvironment("test")
.ConfigureServices(x =>
{
.AddWebEncoders();
});
如果我运行一个简单的测试来检查主页是否可访问它是否有效 .
对于某些存在的问题,我必须在Startup中更改一些配置 . 所以我在WebHostBuilder上的Configure上添加了一个调用:
var builder = new WebHostBuilder()
.UseContentRoot(appRootPath)
.UseStartup<TStartup>()
.UseEnvironment("test")
.ConfigureServices(x =>
{
.AddWebEncoders();
})
.Configure(x => {
// Some specific configuration
});
而且,我不知道为什么(这就是为什么我需要你的帮助),当我像以前一样调试相同的简单测试时,启动类的ConfigureServices和Configure方法永远不会被调用...即使我只是让Configure方法空白 .
这个行为是否正常?
如何在不直接在Startup.cs中添加特定配置的情况下进行设置?
1 回答
WebHostBuilder.Configure替换
UseStartup
,它们不能一起使用 . 相反,您可以在ConfigureServices
内注册IStartupFilter
. 看here .