且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-16 23:19:55

我这样做的:

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, 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方法。

And then I just passed in the bindingContext variable to the BindModel method of the object that implements the IModelBinder interface.