简体   繁体   English

如何在 Controller 中使用 Moq 模拟 HttpContext.Current.Request.Form

[英]How to mock HttpContext.Current.Request.Form using Moq in Controller

How can I mock HttpContext.Current.Request.Form["something"] data in the tested controller?如何在测试的 controller 中模拟 HttpContext.Current.Request.Form["something"] 数据? I can mock HttpContext.Current and it works but Request is readonly.我可以模拟 HttpContext.Current 并且它可以工作,但 Request 是只读的。 I can not change the implementation of the controller where the Form data is used.我无法更改使用表单数据的 controller 的实现。 I only have to write a test.我只需要写一个测试。

If you really can't change the implementation of the controller to use modelbinding, you can mock the request object easily enough:如果你真的不能改变 controller 的实现来使用模型绑定,你可以很容易地模拟请求 object :

var formData = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues> { { "test", "value" } });

var requestMock = new Mock<HttpRequest>();
requestMock.SetupGet(x => x.Form).Returns(formData);

var contextMock = new Mock<HttpContext>();
contextMock.SetupGet(x => x.Request).Returns(requestMock.Object);

Setup FormCollection how you need your example data to look.设置FormCollection您需要如何查看示例数据。

As others have stated, it makes way more sense to use modelbinding since it abstracts away this requirement.正如其他人所说,使用模型绑定更有意义,因为它抽象了这个要求。

Actually, you didn't mention if you were using ASP.NET or Core, I assume .NET based on HttpContext.Current ?实际上,您没有提到您使用的是 ASP.NET 还是 Core,我假设 .NET 基于HttpContext.Current

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM