2013-08-19 116 views
0

我們正在考慮使用MVC3進行一些單元測試。我認爲合理的解決辦法是標記行動以返回「B」視圖並標記其他行爲,以便記錄結果。使用ActionFilterAttribute進行測試

也許控制器是這樣的:

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

在註冊將返回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 IABLogMessenger 
{ 
    void Write(ABLogMessage message); 
} 

這是否看起來是用最少的代碼更改實現這一點的一種合理的方式?

回答

0

這似乎是一個合理的解決方案。我知道這一點,因爲我已經使用這個相同的概念來開發A/B測試框架(http://www.nuget.org/packages/AbTestMaster)。它在nuget上免費提供,並且也是開源的。

這可能會讓你的生活稍微簡單一些。