Mock HttpRequest

Mock HttpRequest HttpContext 有时候我们Controller里面的方法 需要访问 this.Request. 获取里面的Host信息,或者其它的信息, 这个时候我们相测试它的话我们就需要Mock这个对象了。

Asp.net 5.0 测试通过

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;

            var controller = new TestController();

            var request = new Mock<HttpRequest>();
            request.Setup(it => it.Host).Returns(new HostString("www.malema.net"));
            request.Setup(x => x.Form).Returns(new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>()
            {
                ["ourname"] = new Microsoft.Extensions.Primitives.StringValues("malema"),
                ["when"] = new Microsoft.Extensions.Primitives.StringValues("2022-8-18"),
            }));
            request.Setup(x => x.Headers).Returns(new HeaderDictionary(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>()
            {
                ["header1"] = new Microsoft.Extensions.Primitives.StringValues("header1 value"),
            }));

            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.Request).Returns(request.Object);
            var actionContext = new ActionContext(httpContext.Object, new Microsoft.AspNetCore.Routing.RouteData(), new ControllerActionDescriptor());

            var controllerContext = new ControllerContext(actionContext);
            controller.ControllerContext = controllerContext;

            var actionResult = controller.Collect(jObject);
            Assert.IsType<OkObjectResult>(actionResult);
            
下一篇:mock-console
最近更新的
...