Asp .Net Core 3.0 adding a custom Startup class in tests causes that the Views are not served anymore
See original GitHub issueI test an Asp .Net Core 3.0 MVC application. This a basic sample app create with the command dotnet new mvc. In the xunit test project I test returning of the view Index from the HomeController
. The test looks like this:
public class HomeControllerTests
{
[Fact]
public async Task ReturnsView()
{
const string testProjectDir = "ViewsTestingTests";
var factory = new TestServerFactory();
var client = factory.WithWebHostBuilder(builder =>
{
builder.UseSolutionRelativeContentRoot(testProjectDir);
builder.ConfigureTestServices(services =>
{
services.AddControllersWithViews()
.AddApplicationPart(typeof(Startup).Assembly);
});
}).CreateClient();
var resultIndex = await client.GetAsync("/");
resultIndex.StatusCode.Should().Be(200);
var content = await resultIndex.Content.ReadAsStringAsync();
content.Should().Contain("Welcome");
}
}
public class TestServerFactory : WebApplicationFactory<TestStartup>
{
protected override IWebHostBuilder CreateWebHostBuilder()
{
return WebHost.CreateDefaultBuilder(null)
.UseStartup<TestStartup>();
}
}
public class TestStartup : Startup
{
public TestStartup(IConfiguration configuration) : base(configuration)
{
}
}
I use a test startup class because I’ll be overriding some methods. When I use this TestStartup
class the test doesn’t pass with the following reason:
The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml
But if I use the Startup class from the main project like this:
public class TestServerFactory : WebApplicationFactory<Startup>
{
protected override IWebHostBuilder CreateWebHostBuilder()
{
return WebHost.CreateDefaultBuilder(null)
.UseStartup<Startup>();
}
}
And create Client like this:
var client = factory.WithWebHostBuilder(builder =>
{
builder.UseSolutionRelativeContentRoot(testProjectDir);
}).CreateClient();
Then the test pass. Of course I copied the whole Views folder to the test project. What is interesting the same test used to work in Asp. Net Core 2.2.
Using builder.UseContentRoot inside factory.WithWebHostBuilder and setting a path to the test project folder doesn’t help. Please help me how to approach this problem.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:7 (1 by maintainers)
Top GitHub Comments
@mykola384 for me even better solution. I must only add the package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation. Thank you.
I fixed it by adding
services .AddMvc() .AddRazorRuntimeCompilation() .AddApplicationPart(typeof(TTestStartup).Assembly);
But thanks for the suggestion!