3

我使用 MVC3 并想通过Microsoft.VisualStudio.TestTools.UnitTestingand测试以下操作Moq

public ActionResult index()
{
        Session.Add("username", "Simon");
        var lName = Session["username"] as String;
        var lSessionID = Session.SessionID;
        return Content(lSessionID);
}

我的单元测试:

[TestMethod]
public void IndexTest()
{

    // Arrange

    var contextMock = new Mock<ControllerContext>();
    var mockHttpContext = new Mock<HttpContextBase>();

    var session = new Mock<HttpSessionStateBase>();
    mockHttpContext.Setup(ctx => ctx.Session).Returns(session.Object);

    StartController controller = new StartController();

    var lResult = controller.index() as ContentResult;

    Assert......;
}

我的单元测试导致 NullReferenceException:

在此处输入图像描述

我也尝试过MvcContrib.TestHelper失败,Session.SessionID并显示“尚未实现”消息。

如何使用单元测试来测试我的操作?

4

1 回答 1

8

您的模拟设置不完整。

您需要设置ControllerContextc.HttpContext返回您的mockHttpContext,您还需要使用您contextMockStartController设置其ControllerContext 属性:

因此,以下设置应该可以工作:

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);

StartController controller = new StartController();
controller.ControllerContext = contextMock.Object;
于 2013-07-09T08:06:36.243 回答