首页 文章

ASP.Net核心集成测试

提问于
浏览
5

我正在努力使用ASP.Net Core RC2进行任何类型的集成测试 . 我创建了一个基本的Web项目,它在浏览器中运行正常,显示了预期的默认页面 . 然后,我使用以下测试代码添加了一个新类(在同一个项目中):

[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);
    }
}

测试没有通过,但有以下例外:

未找到“索引”视图 . 搜索了以下位置:/Views/Home/Index.cshtml /Views/Shared/Index.cshtml

我在这个阶段使用MSTest而不是xUnit . 不幸的是,将ContentRoot更改为“重复”问题中建议的内容并不能解决问题 .

有没有人进行集成测试?我试过调整 WebHostBuilder 设置,但没有运气 .

1 回答

  • 7

    我写了一篇关于集成测试的博客文章(不包括MVC),而“Snow Crash”则发表了类似问题的评论 . 他们使用以下代码解决了“未找到”错误:

    var path = PlatformServices.Default.Application.ApplicationBasePath;
    var setDir = Path.GetFullPath(Path.Combine(path, <projectpathdirectory> ));
    
    var builder = new WebHostBuilder()
       .UseContentRoot(setDir)
       .UseStartup<TStartup>();
    

    博客文章在这里Introduction to integration testing with xUnit and TestServer in ASP.NET Core .

相关问题