1

我有一个控制器方法,它接受 FormCollection 作为参数。然后控制器方法使用 UpdateModel(Model, new[] { P1, P2 }) 构建模型;

我想对上述方法进行单元测试。我正在使用 P1 和 P2 值填充 formcollection,但是从单元测试调用时模型没有正确构建。

有没有人遇到过类似的问题?

4

1 回答 1

3

UpdateModel方法在Request填充模型时查看对象,它完全忽略了FormCollection您正在传递的内容。因此,您需要模拟请求并将值添加到该对象。但这很多工作不值得付出努力,我会向您推荐一种更好的方法:不要使用FormCollection作为操作参数,然后UpdateModel在您的操作中调用,而是使用强类型操作参数:

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
    ...
}

并且在单元测试中,只需在调用控制器操作时传递所需的模型。

于 2010-12-28T16:51:13.673 回答