【发布时间】:2014-05-29 09:22:31
【问题描述】:
我正在使用 NUnit 和 Moq 进行单元测试。我尝试了这个示例来检查是否存在名为 Role 的会话对象。如果没有,则创建它,并返回 Role 类型的对象。
protected Role GetRole()
{
if (Session["Role"] == null)
{
Session["Role"] = new Role();
}
return Session["Role"] as Role;
}
然后我在索引操作中使用它:
public ActionResult Index()
{
var roles = GetRole();
roles.RoleName = "Test";
return View();
}
这是我的测试:
[Test]
public void TestMethod1()
{
var contextMock = new Mock<ControllerContext>();
var mockHttpContext = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
mockHttpContext.Setup(ctx => ctx.Session).Returns(session.Object);
contextMock.Setup(ctx => ctx.HttpContext).Returns(mockHttpContext.Object);
contextMock.Setup(p => p.HttpContext.Session["Role"]).Returns(new Role
{
RoleId = 1,
RoleName = "Test"
});
var homeController = new HomeController();
homeController.ControllerContext = contextMock.Object;
var indexView = homeController.Index();
Assert.IsNotNull(indexView);
}
运行成功。但是当我检查代码覆盖率时,它给了我 Session["Role"] = new Role();部分未包含在测试代码中。于是我又做了一个测试。那里我没有设置会话变量角色:
[Test]
public void TestMethod2()
{
var contextMock = new Mock<ControllerContext>();
var mockHttpContext = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
mockHttpContext.Setup(ctx => ctx.Session).Returns(session.Object);
contextMock.Setup(ctx => ctx.HttpContext).Returns(mockHttpContext.Object);
var homeController = new HomeController();
homeController.ControllerContext = contextMock.Object;
var indexView = homeController.Index();
Assert.IsNotNull(indexView);
Assert.IsNull(homeController.ControllerContext.HttpContext.Session["Role"]);
}
但它失败了 - 它给出了 System.NullReferenceException : Object reference not set to an instance of an object because the roles.RoleName = "Test";排。如何让它运行? 提前谢谢!
【问题讨论】:
标签: c# asp.net-mvc unit-testing session