【问题标题】:How to unit test MVC Controller Action that calls a service associated with the Controller如何对调用与控制器关联的服务的 MVC 控制器操作进行单元测试
【发布时间】:2015-03-26 06:43:56
【问题描述】:

好的,我试过了。但我无法理解这一点。

我有一个控制器

public sealed class CourseController : ExtController
{
 [HttpPost, PersistState, InRole("")] //TODO [SECURITY] [FIX] UPDATE SECURITY ROLES ]

    public ActionResult Create(string[] flags, string name, string code, string description)
    {
        try
        {
            var Course = Svc.ProcessOperation("CreateCourse", new
            {

                Flags = flags.Merge(",")
            });



            Svc.ProcessOperation("CreateCourseTranslation", new
            {
                CourseId = Course.EntityID,
                LanguageId = JAs.Int32(Svc.Localization.Language.EntityID),
                Name = name,
                Description = description,
                Code = code

            });
            TempData.PersistStatus("Success");

            return View();
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("API", ex);
            TempData.PersistStatus("Failed");
        }
        return RedirectToAction("Create");
    }
}

Svc 是 ExtController 抽象类中 Service 类型的公共属性,它又扩展了 Controller 类

 /// <summary>
/// Represents the exteded controller.
/// </summary>
public abstract class ExtController : Controller
{
    #region Properties

    /// <summary>
    /// Gets the service associated with the controller.
    /// </summary>
    public Service Svc
    {
        get
        {
            return HttpContext.Svc();
        }
    }

    #endregion
}

这是使用 NUnit

的单元测试代码
 [Test]
    public void Create_HttpPost_Action_Returns_Create_View()
    {
        // Arrange          
        var customersController = new CourseController();

        // Act
        var result = customersController.Create(new[] { "None" }, "courseName", "Code", "description") as ViewResult;

        // Assert
        Assert.IsNotNull(result, "Should have returned a ViewResult");
        result.AssertViewRendered().ForView("Create");

    }

T他的问题是调用 Create 方法时需要使用 Svc 来处理操作,所以我想我必须 Mock !但我不知道怎么做。

我应该模拟控制器吗?但我不能,因为它是一个密封的班级!或 ExtController!我迷路了,需要指导。

[FWIW] 这个项目基于Xenta MVC Framework (Open Source),它有这个架构概述

【问题讨论】:

    标签: c# asp.net-mvc unit-testing mocking


    【解决方案1】:

    您不应该模拟控制器,因为这是您要测试的内容。就像你说的,你必须模拟 Svc 属性。一种可能的解决方案是在您的抽象 ExtController 中覆盖该属性,然后在 CourseController 中覆盖它。您现在可以在单元测试中将 Svc 属性设置为模拟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2020-09-05
      • 2016-02-20
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多