如何使用 MSpec 测试 ASP.NET MVC 操作设置的 HTTP 状态代码
我有以下控制器:
public sealed class SomeController : Controller
{
public ActionResult PageNotFound()
{
Response.StatusCode = 404;
return View("404");
}
}
我创建了一个 MSpec 规范:
[Subject(typeof (SomeController))]
public class when_invalid_page_is_requested : SomeControllerSpec
{
Because of = () => result = Controller.PageNotFound();
It should_set_status_code_to_404 =
() => Controller.Response.StatusCode.ShouldEqual(404);
}
public abstract class SomeControllerSpec
{
protected static HomeController Controller;
Establish context = () => { Controller = new SomeController(); };
}
但由于我实例化控制器的方式,HttpContext 为 null。 测试由 PageNotFound
操作设置的状态代码的最佳方法是什么?
编辑:在下面发布了答案
I have the following controller:
public sealed class SomeController : Controller
{
public ActionResult PageNotFound()
{
Response.StatusCode = 404;
return View("404");
}
}
I have created an MSpec specification:
[Subject(typeof (SomeController))]
public class when_invalid_page_is_requested : SomeControllerSpec
{
Because of = () => result = Controller.PageNotFound();
It should_set_status_code_to_404 =
() => Controller.Response.StatusCode.ShouldEqual(404);
}
public abstract class SomeControllerSpec
{
protected static HomeController Controller;
Establish context = () => { Controller = new SomeController(); };
}
But because of how I instantiate the controller, HttpContext is null.
What would be the best way to test status code set by the PageNotFound
action?
EDIT: Posted an answer below
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
找到了一种使用最小起订量来做到这一点的方法。
不是很优雅。如果您能想到更好的方法 - 请告诉我。
Found a way to do it using Moq.
Not very elegant. If you can think of a better way - let me know.
您可以使用:
You can use:
另一种选择是使用 MvcContrib 的 TestControllerBuilder...
然后使用 NUnit(我猜 Moq 版本会起作用)就像你拥有的那样)...
所有丑陋的设置和模拟工作仍在完成,但由 MvcContrib 而不是在测试内部完成。这是一篇关于使用 TestControllerBuilder 的文章。
Another option using MvcContrib's TestControllerBuilder...
and then using NUnit (I'd guess the Moq version would work just like you have it)...
All the ugly setup and mocking work is still being done, but by MvcContrib instead of inside the test. Here's a post on using the TestControllerBuilder.