我尝试设置会话变量以运行某些单元测试时未成功.当我尝试设置会话变量时,我不断收到"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)
但是,当我运行应用程序本身时,没有错误,应用程序正常运行.我确实理解,通过测试驱动开发,测试应该为实现铺平道路.我正在尝试对已经完成的应用程序进行单元测试.如果可能的话,因为应用程序有效,我想避免对我的实现进行任何更改,只需编写一个单元测试来支持我已经知道的内容.