![](/img/trans.png)
[英]How to unit test whether a Core MVC controller action calls ControllerBase.Problem()
[英]How to unit test MVC Controller Action that calls a service associated with the Controller
好吧,我嘗試過。 但是我無法解決這個問題。
我有一個控制器
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");
}
噸他的問題是當創建方法被調用它需要使用SVC處理操作,所以我想我有嘲笑的! 但我不知道如何。
我應該嘲笑控制器! 但我不能因為它是密封班! 或ExtController! 我迷路了,需要指導。
[FWIW]該項目基於具有此體系結構概述的Xenta MVC框架(開源)。
您不應該模擬控制器,因為這就是您要測試的內容。 就像您說的那樣,您必須模擬Svc
屬性。 一種可行的解決方案是使屬性在抽象ExtController
重寫,然后在CourseController
對其進行CourseController
。 現在,您可以在單元測試中將Svc
屬性設置為模擬對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.