【问题标题】:Moq a function call to a different classMoq 对不同类的函数调用
【发布时间】:2013-02-06 05:43:33
【问题描述】:
您好,我需要使用 Moq 模拟以下方法。
[HttpPost]
public ActionResult Create(TagsViewModel tagsViewModel)
{
return RedirectToAction("Index", new { sid = specification.SpecificationId }).Success("Saved Successfully!");
}
但我在上述行中收到了异常。问题是,在那里的 Success() 方法中,它使用了“System.Web.HttpContext”类,而没有模拟代码失败的情况。所以我考虑在测试方法中模拟“成功”方法本身,这样我就不必担心模拟 HttpContext。那可能吗? ('Success()' 方法与测试类在不同的类中)
【问题讨论】:
标签:
c#
asp.net-mvc
unit-testing
moq
【解决方案1】:
你可以试试这样的
[HttpPost]
public ActionResult Create(TagsViewModel tagsViewModel)
{
var someUnknownObj = TestableRedirectToAction(tagsViewModel);
return someUnknownObj.Success("Saved Succesfully");
}
internal someUnknownObjType TestableRedirectToAction(TagsViewModel tagsViewModel)
{
// ................................
// ................................
return RedirectToAction("Index", new { sid = specification.SpecificationId })
}
现在测试承载所有逻辑的 TestableRedirectToAction 方法 - Success()