2009-11-06 105 views
0

在我的應用我有我在Global.asax設置爲DefaultBinder自定義模型綁定:單元測試自定義模型綁定控制器

ModelBinders.Binders.DefaultBinder = new XLDataAnnotationsModelBinder(); 

當編寫單元測試控制器我需要確保控制器使用自定義模型綁定器,但我不知道如何做到這一點。

我的測試是這樣的:

[Test] 
public void Details_Post_Action_Fails_To_Change_Email_Address_With_Duplicate() 
{ 
    // Setup 
    var controller = new AccountController(); 
    controller.SetFakeControllerContext(); 

    var param = Customer.Load(30005); 
    param.EmailAddress = "[email protected]"; 

    // Test 
    var result = controller.Details(param); 

    // Assert 
    Assert.IsTrue(result is ViewResult); // will be ViewResult if failed.... 
    Assert.IsFalse(((ViewResult)result).ViewData.ModelState.IsValid); 
} 

有了這個單元測試控制器結束了使用DefaultModelBinder。我可以在此測試中添加什麼來確保控制器使用自定義模型聯編程序?

回答

3

斯科特Hanselman的取得與此相關的一個,而前一個博客帖子:

Splitting DateTime - Unit Testing ASP.NET MVC Custom Model Binders

會感興趣,你是在後的「測試自定義模型綁定」下底部的一部分。基本上你實例化一個ModelBindingContext,然後實例化你的Modelbinder,並在你創建的ModelBindingContext(如果需要的話)和控制器上下文中傳遞ModelBinder上調用Bind()。

這裏是SO另一個問題也有您需要的(即使你不使用MOQ)的信息:

How to Unit Test a custom ModelBinder using Moq?

+0

出現Hanselman的鏈接是什麼我要找的,所以我標記爲答案。我沒有+1,因爲實際的答案不是在stackoverflow(意思是說,如果hansleman的網站由於某種原因失敗,這個答案沒有價值)。 – 2009-11-11 19:17:14