Asp.net MVC 3 中的单元测试模型更改
我有一个 ProductController
类和一个 Product
模型。每次调用 ProductController
中的 Create
操作时,它都会基于 FormCollection
创建一个新的 Product
,然后调用Product
中的函数用于更改日期:
[HttpPost]
public ActionResult Create(FormCollection form)
{
Product product = new Product();
TryUpdateModel(product, form);
if(ModelState.IsValid)
{
product.ChangeDate(form["date"]);
repository.SaveProduct(product);
return RedirectToAction("Index");
}
else
return View();
}
我想知道如何测试 Product
所以我知道 .ChangeDate
正在被调用(通过 Moq 的 <代码>验证)。我没有使用 Asp.Net 自动模型绑定,因为我想通过 TryUpdateModel
捕获任何绑定异常。我不确定是否应该将 .ChangeDate
放入 Controller 或 Repository 类中。我正在使用 Moq、MVC3 和 Entity Framework 4。如有任何帮助,我们将不胜感激!
谢谢, 亚历克斯
I have a ProductController
class and a Product
model. Everytime the Create
action in the ProductController
is called, it creates a new Product
based on FormCollection
and then it calls a function inside Product
to change a date:
[HttpPost]
public ActionResult Create(FormCollection form)
{
Product product = new Product();
TryUpdateModel(product, form);
if(ModelState.IsValid)
{
product.ChangeDate(form["date"]);
repository.SaveProduct(product);
return RedirectToAction("Index");
}
else
return View();
}
I was wondering how I can test Product
so I know .ChangeDate
is being called (via Moq's Verify
). I did not use the Asp.Net automatic model-binding because I want to catch any binding exception via TryUpdateModel
. I am not sure if i should put .ChangeDate
in the Controller or Repository class. I am using Moq, MVC3, and Entity Framework 4. Any help is appreciated!
Thanks,
Alex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以对模拟存储库的 SaveProduct 方法设置期望,以便使用特定参数调用它。这个特定的参数将是在控制器操作内部构造的产品。然后,您可以断言该对象的
Date
属性与您在表单集合中的Create
操作中作为参数传递的属性相同。You can setup an expectation on the
SaveProduct
method of the mocked repository so that it is called with a specific argument. This specific argument will be the product which is constructed inside the controller action. Then you can assert that theDate
property of this object is the same as the one you passed as argument in theCreate
action in the form collection.