10

我有以下方法:

    public void SetHttpStatusCode(HttpStatusCode httpStatusCode)
    {
        Response.StatusCode = (int)httpStatusCode;
    }

以及以下测试:

    [TestMethod]
    public void SetHttpStatusCode_SetsCorrectStatusCode()
    {
        //Arrange
        //Any url will suffice
        var mockHttpContext = TestHelpers.MakeHttpContext(""); 
        mockHttpContext.SetupSet(x => x.Response.StatusCode = It.IsAny<int>());

        //creates an instance of an asp.net mvc controller
        var controller = new AppController()
        {
         ControllerContext = new ControllerContext() { 
                   HttpContext = mockHttpContext.Object }
                             };

        // Act
        controller.SetHttpStatusCode(HttpStatusCode.OK);

        //Assert
        mockHttpContext.VerifySet(x => x.Response.StatusCode = It.IsAny<int>());
    }

另外,这里是 MakeHttpContext

 public static Mock<HttpContextBase> MakeHttpContext(string url)
    {
        var mockHttpContext = new Mock<HttpContextBase>();
        var mockRequest = new Mock<HttpRequestBase>();
        var mockResponse = new Mock<HttpResponseBase>();
        var mockSession = new Mock<HttpSessionStateBase>();

        //request
        mockRequest.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(url);
        mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);

        //response
        mockResponse.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => x);
        mockHttpContext.Setup(x => x.Response).Returns(mockResponse.Object);

        //session
        mockHttpContext.Setup(x => x.Session).Returns(mockSession.Object);

        return mockHttpContext;
    }

当我运行测试时,我得到以下异常:

    Test method PA.Tests.Controllers.AppControllerTest.SetHttpStatusCode_SetsCorrectStatusCode
threw exception: 


      Moq.MockException: 
        Expected invocation on the mock at least once, 
        but was never performed: x => x.StatusCode = It.IsAny<Int32>()

        Configured setups:
        x => x.StatusCode = It.IsAny<Int32>(), Times.Never
        No invocations performed.

Moq 如何期望/要求调用被调用?我已经调试了 SetHTTPStatusCode 方法,响应对象确实是一个模拟对象,但是 Moq 坚持认为没有调用。我错过了什么吗?

谢谢!

4

1 回答 1

21

你还没有展示你的TestHelpers.MakeHttpContext方法做了什么,所以有点难以理解发生了什么。

试试这样:

// Arrange
var mockHttpContext = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();
mockHttpContext.SetupGet(x => x.Response).Returns(response.Object);

//creates an instance of an asp.net mvc controller
var controller = new AppController()
{
    ControllerContext = new ControllerContext() 
    { 
        HttpContext = mockHttpContext.Object 
    }
};

// Act
controller.SetHttpStatusCode(HttpStatusCode.OK);

//Assert
response.VerifySet(x => x.StatusCode = (int)HttpStatusCode.OK);
于 2012-05-25T14:10:33.963 回答