Startup.cs没有触发

时间:2015-06-25 22:43:36

标签: asp.net config asp.net-core-mvc xunit

我正在尝试测试我的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文件?或者我怎么能解决这个问题?

1 个答案:

答案 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

希望这有帮助!