I am trying to test my MVC project. For the sake of simplicity, in the Startup
class I have:
public static IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var configuration = new Configuration()
.AddJsonFile("config.json");
Configuration = configuration;
}
And I am using this configuration globally, like this:
private static string connectionString = Startup.Configuration["Database:ConnectionString"];
It works, it can find this in the file.
My problem:
When I am running tests, the Startup
class seems to not be firing. Because of that whenever I access Startup.Configuration
, this field is null.
What can I do to fire it so that the config.json
file is read? Or how else could I solve this issue?
The Startup method is typically called when you start up your web server whether it be on IIS Express, Web Listener, Kestrel etc. If you're trying to run tests you need to start a server or test server which will then invoke your Startup method.
Microsoft.AspNet.TestHost
is a great utility to use to create test based servers. In particular theTestServer
I'm speaking of lives here: https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.TestHost/TestServer.csHere's how we use it in MVC: https://github.com/aspnet/Mvc/blob/dev/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs
and an actual test creating a server
https://github.com/aspnet/Mvc/blob/cc4ee1068de55a0948c35f5a87f6c05907cb8461/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultValuesTest.cs#L42
Hope this helps!