gpt4 book ai didi

c# - 使用 Moq 模拟 ControllerBase 请求

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:09 25 4
gpt4 key购买 nike

我在 .Net Core 2.2 中有一个 Web API,如下所示:

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class SomeController : ControllerBase
{
[HttpPost]
public async Task<string> SomeMethodPost()
{
string returnUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/some/redirect";

//Some Third Part Service Call

return serviceResult;
}
}

我想在我的单元测试中为我的 Controller 操作模拟属性“Scheme”、“Host”和“PathBase”。我设法在我的单元测试方法中编写了以下代码:

var request = new Mock<HttpRequest>(MockBehavior.Strict);
request.Setup(x => x.Scheme).Returns("http");
request.Setup(x => x.Host).Returns(HostString.FromUriComponent("http://localhost:8080"));
request.Setup(x => x.PathBase).Returns(PathString.FromUriComponent("/api"));

var mockHttp = new Mock<ControllerBase>(MockBehavior.Strict);
mockHttp.SetupGet(x => x.Request).Returns(request.Object);

但是,最后一行中的模拟会抛出异常,因为“ControllerBase”的“Request”是不可覆盖的。我了解抽象类的非虚拟属性的局限性。有什么解决方法吗?

最小起订量版本为 4.13.0。

最佳答案

改变方法。不要 mock 被测对象,在本例中是 Controller 。

Controller 的 Request 是通过 HttpContext 访问的,可以在安排测试时设置。

例如

//Arrange
var request = new Mock<HttpRequest>();
request.Setup(x => x.Scheme).Returns("http");
request.Setup(x => x.Host).Returns(HostString.FromUriComponent("http://localhost:8080"));
request.Setup(x => x.PathBase).Returns(PathString.FromUriComponent("/api"));

var httpContext = Mock.Of<HttpContext>(_ =>
_.Request == request.Object
);

//Controller needs a controller context
var controllerContext = new ControllerContext() {
HttpContext = httpContext,
};
//assign context to controller
var controller = new SomeController(){
ControllerContext = controllerContext,
};

String expected = "expected value here";

//Act
String actual = await controller.SomeMethodPost();


//Assert
Assert.AreEqual(expected, actual);

//...

关于c# - 使用 Moq 模拟 ControllerBase 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315425/

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