在 ASP.net MVC 单元测试中访问 ModelState 错误字典中的错误消息
我在操作结果中添加了一个键值对,如下所示:
[HttpPost, Authorize] public ActionResult ListFacilities(int countryid) { ... ModelState.AddModelError("Error","No facilities reported in this country!"); ... }
我在单元测试中有一些像这样的繁琐代码:
public void ShowFailforFacilities() { //bogus data var facilities = controller.ListFacilities(1) as PartialViewResult; Assert.AreSame("No facilities reported in this country!", facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage); }
当然,只要我只有一个错误,它就可以工作。
我不喜欢facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage
。
有没有更简单的方法可以从该字典中获取值?
I have added a key-value pair in the action result like this:
[HttpPost, Authorize] public ActionResult ListFacilities(int countryid) { ... ModelState.AddModelError("Error","No facilities reported in this country!"); ... }
I have some cumbersome codes like these in a unit test to :
public void ShowFailforFacilities() { //bogus data var facilities = controller.ListFacilities(1) as PartialViewResult; Assert.AreSame("No facilities reported in this country!", facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage); }
Of course, it works whenever I have only one error.
I don't like facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage
.
Is there an easier way for me to fetch the value from that dictionary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不需要您的 FirstOrDefault,因为您在访问 ErrorMessage 时会收到 NullReferenceException。您只需使用 First() 即可。
不管怎样,我找不到任何内置的解决方案。相反,我所做的是创建一个扩展方法:
其工作原理如下:
如果您需要更好的异常处理,或支持多个错误,它很容易扩展...
如果您希望它更短,您可以创建一个扩展方法对于 ViewData...
和用法:
Your FirstOrDefault isn't needed, because you'll get a NullReferenceException when accessing ErrorMessage. You can just use First().
Either way, I couldn't find any built-in solution. What I've done instead is create an extension method:
Which works like this:
If you need better exception handling, or support for multiple errors, its easy to extend...
If you want this to be shorter you can create an extension method for the ViewData...
and usage:
你试过这个吗?
Have you tried this?