通过使用ActionFilterAttribute进行ABTesting

时间:2013-08-19 15:38:37

标签: asp.net-mvc-3 ab-testing actionfilterattribute

我们正在考虑使用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视图,确认将记录使用的视图。

该属性看起来像这样:

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);
}

这似乎是通过最少的代码更改来实现此目的的合理方法吗?

1 个答案:

答案 0 :(得分:0)

这似乎是一个合理的解决方案。我知道这是因为我使用了同样的概念来开发A / B测试框架(http://www.nuget.org/packages/AbTestMaster)。它在nuget上免费提供,也是开源的。

这可能会让你的生活变得更加简单。

相关问题