无法设置会话变量

Ada*_*rtz 3 c# asp.net-mvc unit-testing

我尝试设置会话变量以运行某些单元测试时未成功.当我尝试设置会话变量时,我不断收到"System.NullReferenceException:对象引用未设置为对象实例"的错误.

这是我正在构建的测试:

[TestMethod]
public void MyMethod()
{
  //Arrange
  int id = 12345;
  string action = "A";
  string comment = "";
  string user = "user";
  var controller = new MyController();

  //Act
  controller.Session["altUser"] = user;
  var result = controller.Process(id, action, comment);

  //Assert
  Assert.IsNotNull(result);     
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

[Authorize]
public class MyController : Controller
{
  public ActionResult Process(int id, string action, string comment)
  {
    string userId = Session["altUser"].ToString();
    //some other stuff that evaluates ID, Action, and Comment
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行应用程序本身时,没有错误,应用程序正常运行.我确实理解,通过测试驱动开发,测试应该为实现铺平道路.我正在尝试对已经完成的应用程序进行单元测试.如果可能的话,因为应用程序有效,我想避免对我的实现进行任何更改,只需编写一个单元测试来支持我已经知道的内容.

Col*_*kay 8

控制器从HttpContext单元测试中获取会话,这就是失败的原因.

但是,您可以模拟HttpContext并在其中放置模拟会话.

像这样的东西可能会起作用(使用moq作为Mocking框架)

    var mockControllerContext = new Mock<ControllerContext>();
    var mockSession = new Mock<HttpSessionStateBase>();
    mockSession.SetupGet(s => s["altUser"]).Returns("user");
    mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);

    var controller = new MyController();
    controller.ControllerContext = mockControllerContext.Object;
Run Code Online (Sandbox Code Playgroud)

你显然需要在模拟对象中填写你真正希望得到的细节.

您还可以从中派生自己的类HttpSessionStateBase,HttpContextBase并使用它们而不是真实会话.