我有一个如下的 .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;
}
}
我希望在我的单元测试中模拟控制器操作的属性"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
" 无法被重写。我理解抽象类中非虚属性的限制。是否有任何解决方法?Moq版本为4.13.0。
request.Setup(x => x.Host).Returns(HostString.FromUriComponent("localhost:8080"));
- ChronoZZ