我们正在考虑使用 MVC3 进行一些单元测试。我认为一个合理的解决方案是标记操作以返回“B”视图并标记其他操作以便可以记录结果。
也许控制器看起来像这样:
[AB(ABModes.View)]
public ActionResult SignUp()
{
return View();
}
[HttpPost]
public ActionResult SignUp(int id)
{
return RedirectToAction("Confirmation");
return View();
}
[AB(ABModes.Result)]
public ActionResult Confirmation()
{
return View();
}
SignUp 将返回 A 或 B 视图,而 Confirmation 将记录使用了哪个视图。
该属性看起来像这样:
using System;
using System.Web.Mvc;
namespace ABTesting.lib
{
public class ABAttribute : ActionFilterAttribute
{
private ABModes mode;
private Abstract.IABChooser abChooser;
private Abstract.IABLogMessenger abMessenger;
public ABAttribute(ABModes mode) : this(mode, new Concrete.ABChooser(), null)
{
}
public ABAttribute(ABModes mode, Abstract.IABChooser abChooser, Abstract.IABLogMessenger abMessenger)
{
this.mode = mode;
this.abChooser = abChooser;
this.abMessenger = abMessenger;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var result = filterContext.Result as ViewResultBase;
var action = filterContext.Controller.ControllerContext.RouteData.Values["action"].ToString();
var actionName = String.IsNullOrEmpty(result.ViewName) ? action : result.ViewName;
if(mode == ABModes.View)
result.ViewName = String.Format("{0}{1}", actionName, abChooser.UseB()? "_B" : String.Empty);
else{
var controller = filterContext.Controller.ControllerContext.RouteData.Values["controller"].ToString();
if (abMessenger != null)
abMessenger.Write(new Entities.ABLogMessage
{
DateCreated = DateTime.Now,
ControllerName = controller,
ActionName = actionName,
IsB = abChooser.UseB()
});
}
base.OnActionExecuted(filterContext);
}
}
}
和
public interface IABChooser
{
bool UseB();
}
和
public interface IABLogMessenger
{
void Write(ABLogMessage message);
}
这似乎是一种以最少的代码更改来完成此任务的合理方法吗?