我正在尝试测试我的MVC项目。为简单起见,在Startup
课程中我有:
public static IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var configuration = new Configuration()
.AddJsonFile("config.json");
Configuration = configuration;
}
我在全球范围内使用此配置,如下所示:
private static string connectionString = Startup.Configuration["Database:ConnectionString"];
它可以工作,它可以在文件中找到它。
我的问题:
当我运行测试时,Startup
类似乎没有被触发。因此,每当我访问Startup.Configuration
时,此字段为空。
我可以做什么来解雇它以便读取config.json
文件?或者我怎么能解决这个问题?
答案 0 :(得分:1)
启动Web服务器时通常会调用Startup方法,无论它是在IIS Express,Web Listener,Kestrel等上。如果您正在尝试运行测试,则需要启动服务器或测试服务器,然后再调用你的启动方法。
Microsoft.AspNet.TestHost
是一个很棒的实用工具,用于创建基于测试的服务器。特别是TestServer
我在这里谈到生活:https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.TestHost/TestServer.cs
以下是我们在MVC中使用它的方式:
https://github.com/aspnet/Mvc/blob/dev/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs
以及创建服务器的实际测试
https://github.com/aspnet/Mvc/blob/cc4ee1068de55a0948c35f5a87f6c05907cb8461/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultValuesTest.cs#L42
希望这有帮助!