gpt4 book ai didi

c# - 我怎样才能用最小起订量模拟 Response.StatusCode?

转载 作者:可可西里 更新时间:2023-11-01 08:57:46 25 4
gpt4 key购买 nike

我有以下方法:

    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 坚持认为没有调用。我错过了什么吗?

谢谢!

最佳答案

您还没有展示您的 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);

关于c# - 我怎样才能用最小起订量模拟 Response.StatusCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10755783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com