【发布时间】:2012-01-26 17:08:00
【问题描述】:
public abstract class MyControllerBase : Controller
{
protected override void OnActionExecuting(ActionExecutingContext context)
{
// do some magic
}
}
我所有的控制器都继承自 MyControllerBase。问题是现在我无法对某些方法进行单元测试,因为过滤器设置了一些影响代码路径的授权/逻辑标志。
有没有办法手动触发OnActionExecuting?管道如何触发这些事件?
编辑:更多地展示这个设计背后的想法,以响应 cmets。我基本上是这样的:
public abstract class MyControllerBase : Controller
{
protected override void OnActionExecuting(ActionExecutingContext context)
{
UserProperties =
_userService
.GetUserProperties(filterContext.HttpContext.User.Identity.Name);
ViewBag.UserProperties = UserProperties;
}
public UserProperties { get; private set; }
public bool CheckSomethingAboutUser()
{
return UserProperties != null
&& UserProperties.IsAuthorisedToPerformThisAction;
}
// ... etc, other methods for querying UserProperties
}
所以现在在View 或Controller 的任何地方,我都可以获取当前用户的详细信息、他们的电子邮件地址、他们的授权、他们工作的部门等等。
例子:
public class PurchasingController : MyControllerBase
{
public ActionResult RaisePurchaseOrder(Item item)
{
// can use UserProperties from base class to determine correct action...
if (UserProperties.CanRaiseOrders)
if (UserProperties.Department == item.AllocatedDepartment)
}
}
所以这个设计真的很好用,但正如你所见,测试上述动作很困难,因为我无法在测试设置中直接操作UserProperties。
【问题讨论】:
标签: asp.net asp.net-mvc-3 unit-testing events protected