以便它不为空从单元测试

以便它不为空从单元测试

本文介绍了如何嘲笑的HttpContext,以便它不为空从单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个单元测试和控制器方法抛出一个异常,因为HttpContext的/ ControllerContext为空。我并不需要从HttpContext的断言什么,只需要它是不为NULL。我已经做了研究,我相信,起订量就是答案。但这一切,我所看到的样品都没有帮了我很多。我不需要做什么特别的,只是嘲笑HttpContext的。点我在正确的方向!

I am writing a unit test and the controller method is throwing an exception because HttpContext / ControllerContext is null. I don't need to assert anything from the HttpContext, just need it to be not NULL. I have done research and I believe Moq is the answer. But all the samples that I have seen haven't helped me a lot. I don't need to do anything fancy, just to mock the httpcontext. Point me in the right direction!

推荐答案

得到的中的一类;

public static class HttpContextFactory
    {
        public static void SetFakeAuthenticatedControllerContext(this Controller controller)
        {

            var httpContext = FakeAuthenticatedHttpContext();
            ControllerContext context =
            new ControllerContext(
            new RequestContext(httpContext,
            new RouteData()), controller);
            controller.ControllerContext = context;

        }


        private static HttpContextBase FakeAuthenticatedHttpContext()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();
            var user = new Mock<IPrincipal>();
            var identity = new Mock<IIdentity>();

            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session.Object);
            context.Setup(ctx => ctx.Server).Returns(server.Object);
            context.Setup(ctx => ctx.User).Returns(user.Object);
            user.Setup(ctx => ctx.Identity).Returns(identity.Object);
            identity.Setup(id => id.IsAuthenticated).Returns(true);
            identity.Setup(id => id.Name).Returns("a.ali174");

            return context.Object;
        }


    }

从单元测试我打电话给他们这样;

From the unit test I called them as such;

 HttpContextFactory.SetFakeAuthenticatedControllerContext(controller);

请确保您已安装在您的测试项目:

Make sure you have Moq installed in your tests project:

Install-Package Moq

这篇关于如何嘲笑的HttpContext,以便它不为空从单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:22