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

前端之家收集整理的这篇文章主要介绍了如何在ASP.NET MVC中测试自定义模型绑定器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在ASP.NET MVC应用程序中编写了一些自定义模型绑定器(实现IModelBinder)。我想知道什么是一个好的方法来对它们进行单元测试(binder)?

解决方法

我这样做:
var formElements = new NameValueCollection() { {"FirstName","Bubba"},{"MiddleName",""},{"LastName","Gump"} };         
var fakeController = GetControllerContext(formElements);
var valueProvider = new Mock<IValueProvider>();           

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



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

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

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

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

原文链接:https://www.f2er.com/aspnet/253135.html

猜你在找的asp.Net相关文章