当前位置:  开发笔记 > 后端 > 正文

如何在ASP.NET MVC中测试自定义模型绑定器?

如何解决《如何在ASP.NETMVC中测试自定义模型绑定器?》经验,为你挑选了2个好方法。

我在ASP.NET MVC应用程序中编写了一些自定义模型绑定器(实现IModelBinder).我想知道对它们进行单元测试的好方法(粘合剂)?



1> Korbin..:

我是这样做的:

var formElements = new NameValueCollection() { {"FirstName","Bubba"}, {"MiddleName", ""}, {"LastName", "Gump"} };         
var fakeController = GetControllerContext(formElements);
var valueProvider = new Mock();           

var bindingContext = new ModelBindingContext(fakeController, valueProvider.Object, typeof(Guid), null, null, null, null);



private static ControllerContext GetControllerContext(NameValueCollection form) {
    Mock mockRequest = new Mock();
    mockRequest.Expect(r => r.Form).Returns(form);

    Mock mockHttpContext = new Mock();
    mockHttpContext.Expect(c => c.Request).Returns(mockRequest.Object);

    return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock().Object);
}

然后我将bindingContext变量传递给实现IModelBinder接口的对象的BindModel方法.


用于ModelBindingContext的contructor重载似乎不存在.

2> Scott Hansel..:

这是我在博客上为您编写的一种简单的无模式方法,假设您使用的是ValueProvider而不是HttpContext:http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx

[TestMethod]  
public void DateTime_Can_Be_Pulled_Via_Provided_Month_Day_Year_Hour_Minute_Second_Alternate_Names()  
{  
    var dict = new ValueProviderDictionary(null) {   
            { "foo.month1", new ValueProviderResult("2","2",null) },  
            { "foo.day1", new ValueProviderResult("12", "12", null) },  
            { "foo.year1", new ValueProviderResult("1964", "1964", null) },  
            { "foo.hour1", new ValueProviderResult("13","13",null) },  
            { "foo.minute1", new ValueProviderResult("44", "44", null) },  
            { "foo.second1", new ValueProviderResult("01", "01", null) }  
        };  

    var bindingContext = new ModelBindingContext() { ModelName = "foo", ValueProvider = dict };  

    DateAndTimeModelBinder b = new DateAndTimeModelBinder() { Month = "month1", Day = "day1", Year = "year1", Hour = "hour1", Minute = "minute1", Second = "second1" };  

    DateTime result = (DateTime)b.BindModel(null, bindingContext);  
    Assert.AreEqual(DateTime.Parse("1964-02-12 13:44:01"), result);  
}  


这是[答案的MVC 2更新](http://stackoverflow.com/questions/1992629/unit-testing-custom-model-binder-in-asp-net-mvc-2/2310954#2310954)在他们找到之前就到此为止.
推荐阅读
手机用户2502852037
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有