【发布时间】:2011-12-31 04:34:00
【问题描述】:
在测试我的控制器的操作时,ModelState 始终有效。
public class Product
{
public int Id { get; set; }
[Required]
[StringLength(10)]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public decimal Price { get; set; }
}
还有我的控制器。
public class ProductController : Controller
{
[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Do some creating logic...
return RedirectToAction("Display");
}
return View(product);
}
}
并测试:
[Test]
public TestInvalidProduct()
{
var product = new Product();
var controller = new ProductController();
controller.Create(product);
//controller.ModelState.IsValid == true
}
当产品没有名称、描述和价格时,为什么modelState有效?
【问题讨论】:
-
您将控制器操作作为普通方法调用,而不是通过 MVC“堆栈”进行模型绑定和验证。
-
@RichardD 那么我如何知道模型状态在动作中完成工作?我必须用单元测试来测试它
-
我不知道 :D 这就是为什么我没有将此作为答案发布。 dskh 的回答可能会对您有所帮助。
-
Unit tests on MVC validation 的可能重复项
-
如果您的控制器的逻辑依赖于任何错误的存在,您应该通过在其 ModelState 中添加测试错误来安排控制器。您的模型的实际验证应单独测试。当然,如果您的控制器应该对特定错误做出反应,只需将该错误添加到 ModelState
标签: c# asp.net-mvc asp.net-mvc-3 unit-testing modelstate