Arn*_*kas 5 c# unit-testing moq mspec asp.net-mvc-3
我有以下控制器:
public sealed class SomeController : Controller
{
public ActionResult PageNotFound()
{
Response.StatusCode = 404;
return View("404");
}
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个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(); };
}
Run Code Online (Sandbox Code Playgroud)
但是由于我实例化控制器的方式,HttpContext为null.测试PageNotFound动作设置的状态代码的最佳方法是什么?
编辑:发布以下答案
找到了一种使用Moq的方法.
[Subject(typeof (SomeController))]
public class when_invalid_page_is_requested : SomeControllerSpec
{
Because of = () => result = Controller.PageNotFound();
It should_set_status_code_to_404 =
() => HttpResponse.VerifySet(hr => hr.StatusCode = 404);
}
public abstract class SomeControllerSpec
{
protected static SomeController Controller;
protected static Mock<ControllerContext> ControllerContext;
protected static Mock<HttpResponseBase> HttpResponse;
Establish context = () =>
{
ControllerContext = new Mock<ControllerContext>();
HttpResponse = new Mock<HttpResponseBase>();
ControllerContext.SetupGet(cc => cc.HttpContext.Response)
.Returns(HttpResponse.Object);
Controller = new SomeController
{
ControllerContext = ControllerContext.Object
};
};
}
Run Code Online (Sandbox Code Playgroud)
不是很优雅.如果你能想到更好的方式 - 让我知道.
| 归档时间: |
|
| 查看次数: |
3601 次 |
| 最近记录: |