.net core asp.net unit tests that depend on files - appsettings.json - fail in travis
MVC's own functional/integration tests are a good example of how you can do this.
MvcTestFixture: (Notice the 'contentRoot' is calculated)https://github.com/aspnet/Mvc/blob/1.0.0/test/Microsoft.AspNetCore.Mvc.FunctionalTests/MvcTestFixture.cs
Example of how it's used in a test:https://github.com/aspnet/Mvc/blob/1.0.0/test/Microsoft.AspNetCore.Mvc.FunctionalTests/BasicTests.cs
Website or App against which the above test verifies:https://github.com/aspnet/Mvc/tree/1.0.0/test/WebSites/BasicWebSite
You should add
"buildOptions": { "copyToOutput": [ "appsettings.json" ] }
to your integration test project project.json,then .SetBasePath(env.ContentRootPath)
will work, since when running the tests - appsettings.json will be at \test\IntegrationTestsProject\bin\Debug\netcoreapp1.1 - where the startup look for it.
After a series of attempts, I found a possible solution. Since I need database initiation, I derived the main Startup
. Several virtual functions inside the TestStartup
are used to initiate the database. Then I make the Configuration
inside the main Startup
class protected settable. Finally:
public TestStartup(IHostingEnvironment env) : base(env){ string basePath = Directory.GetCurrentDirectory(); if (!Directory.GetCurrentDirectory().EndsWith("IntegrationTest")) { basePath = Path.Combine(basePath, "MyProject.IntegrationTest"); } var builder = new ConfigurationBuilder(); builder.SetBasePath(basePath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); builder.AddEnvironmentVariables(); Configuration = builder.Build();}
Although the basePath
fetching is a little ugly, this solution works for me.