ASP.Net Core Integration Testing

2020-03-21 10:19发布

问题:

I'm struggling to get any sort of integration tests working with ASP.Net Core RC2. I have created a basic web project which runs fine in the browser showing the default page as expected. I then added a new class (in the same project) with the following test code:

[TestClass]
public class HomeControllerTests
{
    private HttpClient client;

    [TestInitialize]
    public void Initialize()
    {
        // Arrange
        var host = new WebHostBuilder()
           .UseEnvironment("Development")
           .UseKestrel()
           .UseContentRoot(Directory.GetCurrentDirectory())
           .UseIISIntegration()
           .UseStartup<Startup>();

        TestServer server = new TestServer(host);

        client = server.CreateClient();
    }


    [TestMethod]
    public async Task CheckHomeIndex()
    {
        string request = "/";

        var response = await client.GetAsync(request);

        response.EnsureSuccessStatusCode();

        Assert.IsTrue(true);
    }
}

The test does not pass, with the following exception:

The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml

I'm using MSTest as opposed to xUnit at this stage. Changing the ContentRoot to that suggested in the "duplicate" question unfortunately does not resolve the issue.

Has anyone got integration tests working? I've tried tweaking the WebHostBuilder settings but with no luck.

回答1:

I wrote a blog post on integration testing (not covering MVC), and 'Snow Crash' commented with a similar problem. They solved the 'not found' error with the following code:

var path = PlatformServices.Default.Application.ApplicationBasePath;
var setDir = Path.GetFullPath(Path.Combine(path, <projectpathdirectory> ));

var builder = new WebHostBuilder()
   .UseContentRoot(setDir)
   .UseStartup<TStartup>();

The blog post is here Introduction to integration testing with xUnit and TestServer in ASP.NET Core.