ASP.NET MVC : testing a controller with XUnit

标签 asp.net unit-testing asp.net-core-mvc xunit

我正在尝试使用 XUnit 对 ASP.NET v5 MVC v6 应用程序进行单元测试。我可以对工作方法进行简单的单元测试。我想测试 Controller 。现在,我有一个带有 Index 操作的 HomeController,该操作返回 Home/Index View 。我想测试 Index View 是否是返回的 View 。

这是我当前的测试文件:

using Microsoft.AspNet.Mvc;
using Xunit;
using XUnitWithMvcSample.Controllers;

namespace XUnitWithMvcSample.Tests
{
    public class Tests
    {
        private HomeController _homeController;
        public Tests()
        {
            _homeController = new HomeController();
        }
        [Fact]
        public void IndexActionReturnsIndexView()
        {
            var result = _homeController.Index() as ViewResult;
            System.Console.WriteLine(result);
            Assert.Equal("Index", result.ViewName);
        }

    }
}

这是 Controllers/HomeController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;


namespace XUnitWithMvcSample.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

当我运行测试时,它失败了,因为 result.ViewName 为空。看起来result只是一个空的ViewResult,与_homeController无关。我需要做什么才能让测试在 HomeController 中找到 Index View ?

最佳答案

听起来您正在尝试测试框架中的功能,而不是方法中的功能。该方法中的所有内容如下:

return View();

因此,从字面上看,只要返回非 null ViewResult,该方法就会执行预期的操作:

// Arrange
var controller = new HomeController();

// Act
var result = controller.Index() as ViewResult;

// Assert
Assert.IsNotNull(result);

将该结果链接到 View 是 ASP.NET MVC 框架的一部分,并且发生在该方法之外。这意味着它不是方法调用本身的一部分,而是发生在方法的范围之外。这使其超出了测试范围。

您必须设置一种正在运行的 ASP.NET MVC 应用程序并测试该应用程序才能测试该功能,这更像是黑盒测试而不是单元测试。

关于ASP.NET MVC : testing a controller with XUnit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34775868/

相关文章:

asp.net-core - 如何 "nest"现有 MVC 核心站点内的 MVC 核心应用程序

c# - 有没有办法在.NET Core FilterAttribute 中获取请求正文?

asp.net-core - .NET Core API 请求与支持的文件类型不匹配

asp.net - VSTS 构建失败 - 错误 : Web deployment task failed

javascript - mocha 如何知道事件何时在 $promise 内使用 $broadcast 在 Controller $scope 上触发?

c# - 单元测试 API 调用

javascript - 如何在 react 组件中使用 Jest 和 enzyme 来检查函数是否有参数而不检查其值?

asp.net - 如何解决错误 : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

c# - Closedxml:无法下载文件并立即通过邮件发送

c# - RenderPartial 和 RenderPage 有区别吗?