开发者

MVC Unit Testing Controller Method with FormCollection argument

开发者 https://www.devze.com 2023-02-01 18:10 出处:网络
I am having a controller method which accepts FormCollection as a parameter. the controller method then builds the model using UpdateModel(Model, new[] { P1, P2 });

I am having a controller method which accepts FormCollection as a parameter. the controller method then builds the model using UpdateModel(Model, new[] { P1, P2 });

I wou开发者_如何学Cld like to unit test the above method. I am populating the formcollection with P1 and P2 values but the model is not build correctly when called from unit testing.

Has anyone faced similar issue?


The UpdateModel method looks in the Request object when populating the model and it completely ignores this FormCollection you are passing. So you will need to mock the request and add the values to this object. But thats lots of work that isn't worth the efforts and I would recommend you a better way: instead of using FormCollection as action parameter and then calling UpdateModel inside your action use a strongly typed action parameter:

public ActionResult Foo(SomeViewModel model)
{
    // The model binder will automatically call UpdateModel and populate
    // the model from the request so that you don't need to manually
    // do all this stuff
    ...
}

and in the unit test simply pass the desired model when invoking the controller action.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号