【问题标题】:asp.net 5 vnext integration testing and viewsasp.net 5 vnext 集成测试和视图
【发布时间】:2016-01-22 19:27:18
【问题描述】:

我正在使用带有 MVC6 的 ASP.NET 5 构建一个新应用程序,并尝试设置一个基于 this 描述的测试项目。

API 调用(返回 ObjectResults)工作正常,但是当我点击返回视图的响应时,我得到 404 响应。

我正在使用未测试项目中的启动类,代码与教程中的相同:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseIISPlatformHandler();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");


        }

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

    }

    public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}

[Route("/")]
public class HomeController : Controller
{

    [HttpGet]
    [AllowAnonymous]
    [Route("/")]
    public IActionResult Index()
    {
        return View();
    }

    [HttpGet]
    [AllowAnonymous]
    [Route("/ok")]
    public IActionResult Ok()
    {
        return new ObjectResult("OK");
    }

}

[TestClass]
public class HomeTests
{
    private readonly HttpClient _client;

    public HomeTests()
    {
        var server = new TestServer(TestServer.CreateBuilder()
            .UseStartup<Startup>());
        _client = server.CreateClient();
    }

    [TestMethod]
    public async Task Index_returns_page()
    {
        var response = await _client.GetAsync("/");
        response.EnsureSuccessStatusCode();

        var responseString = await response.Content.ReadAsStringAsync();
        //Assert.Equals("OK", responseString);
    }

    [TestMethod]
    public async Task Index_OK_returns_OK()
    {
        var response = await _client.GetAsync("/ok");
        response.EnsureSuccessStatusCode();

        var responseString = await response.Content.ReadAsStringAsync();
        Assert.AreEqual("OK", responseString);
    }
}

当然,在浏览器中一切都按预期工作。

【问题讨论】:

  • 你能分享你在UseStartup&lt;&gt;中使用的Startup的代码
  • 我添加了完整的启动和测试类代码
  • 控制器是否正确?它在浏览器中工作吗?你试过调试你的控制器吗?
  • 我添加了控制器代码。在浏览器中一切正常。同时测试 /ok 是否正确通过

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

它找不到您的视图,因为 IApplicationEnvironment.ApplicationBasePath 设置为测试项目的目录。您应该将 IApplicationEnvironment 实现替换为您自己的实现,该实现指向您正在测试的项目。这在 RC2 中会变得容易一些。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多