【问题标题】:Unit test a controller with custom model binder使用自定义模型绑定器对控制器进行单元测试
【发布时间】:2009-11-07 20:55:04
【问题描述】:

在我的应用程序中,我有一个自定义模型绑定器,我将其设置为 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 = "foo@bar.com";

     // 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。我可以在这个测试中添加什么来确保控制器使用自定义模型绑定器?

【问题讨论】:

    标签: asp.net-mvc unit-testing controller model-binding


    【解决方案1】:

    Scott Hanselman 不久前发表了一篇与此相关的博文:

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

    您感兴趣的部分位于文章底部的“测试自定义模型绑定器”下。基本上,您实例化一个 ModelBindingContext,然后实例化您的 Modelbinder 并在您的 Modelbinder 上调用 Bind(),传入您创建的 ModelBindingContext(以及控制器上下文,如果需要)。

    这是 SO 的另一个问题,其中也包含您需要的信息(即使您没有使用 Moq):

    How to Unit Test a custom ModelBinder using Moq?

    【讨论】:

    • 汉塞尔曼链接似乎是我正在寻找的,所以我将其标记为答案。我没有 +1,因为实际答案不在 stackoverflow 上(这意味着如果 hansleman 的网站由于某种原因关闭,这个答案没有价值)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多