C# 模拟HttpContext(会话)
C# 模拟HttpContext(会话),c#,asp.net-mvc,unit-testing,mocking,httpcontext,C#,Asp.net Mvc,Unit Testing,Mocking,Httpcontext,我读过很多关于mvc中模拟的文章和博客。。。他们中的许多人都很有帮助,但我仍然有一些问题: 其中一个问题是,我需要在ActionResult中使用会话,但在测试中,当访问会话时,我会得到一个NullReferenceException public ActionResult Index() { if (Session["Something"] == null) { Session.Add("Something", <smth>); } else {
我读过很多关于mvc中模拟的文章和博客。。。他们中的许多人都很有帮助,但我仍然有一些问题:
- 其中一个问题是,我需要在ActionResult中使用会话,但在测试中,当访问会话时,我会得到一个NullReferenceException
public ActionResult Index() { if (Session["Something"] == null) { Session.Add("Something", <smth>); } else { Session["Something"] = <smth>; } return redirect to action("Index2"); }
[Test]
public void AddSessionStarShouldSaveFormToSession()
{
TestControllerBuilder builder = new TestControllerBuilder();
StarsController controller = new StarsController();
builder.InitializeController(controller);
//note that this is assigned before the controller action. This simulates the server filling out the form data from the request
builder.Form["NewStarName"] = "alpha c";
//this assumes that AddSessionStar takes the form data and adds it to the session
controller.AddSessionStar();
Assert.AreEqual("alpha c", controller.HttpContext.Session["NewStarName"]);
}
这只是一个使用会话值的手动测试。。。我需要测试所有的结果。而不是会话是测试点。我需要执行此操作提供的路由(操作\查看名称)。。。我只有一个nullref例外。我需要一个方法,只提供一个未启动的操作来使用一个会话,它不是空的object@AkmecNurikTestHelper还将解决这个NullReference问题,TestControllerBuilder将为您填充模拟实现。
[Test]
public void AddSessionStarShouldSaveFormToSession()
{
TestControllerBuilder builder = new TestControllerBuilder();
StarsController controller = new StarsController();
builder.InitializeController(controller);
//note that this is assigned before the controller action. This simulates the server filling out the form data from the request
builder.Form["NewStarName"] = "alpha c";
//this assumes that AddSessionStar takes the form data and adds it to the session
controller.AddSessionStar();
Assert.AreEqual("alpha c", controller.HttpContext.Session["NewStarName"]);
}