动作过滤器的 ASP.NET MVC 测试 [英] ASP.NET MVC test for action filters

查看:70
本文介绍了动作过滤器的 ASP.NET MVC 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为动作过滤器编写测试用例?我正在使用表单身份验证.我有用 RequiresAuthentication 操作过滤器装饰的基本控制器.当我执行控制器的测试用例时,我没有从 cookie 中获取登录用户的数据.

How can i write test case for action filters? I am using forms authentication. I have base controller decorated with RequiresAuthentication action filter. When i execute the controller's test case, i am not getting the loggedin user's data from the cookies.

我正在使用最小起订量;它是否提供了实现我的目标的方法?

I am using Moq; does it provide a way to achieve my goal?

推荐答案

这篇博文 来自 Scott Hanselmann 的 MvcMockHelpers 包括用于不同模拟框架的 FakeHttpContext 以及 Moq:

This blog post from Scott Hanselmann covers MvcMockHelpers including FakeHttpContext for different mocking frameworks among others also Moq:

using System;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Specialized;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;

namespace UnitTests
{
    public static class MvcMockHelpers
    {
        public static HttpContextBase FakeHttpContext()
        {
            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>();

            context.Expect(ctx => ctx.Request).Returns(request.Object);
            context.Expect(ctx => ctx.Response).Returns(response.Object);
            context.Expect(ctx => ctx.Session).Returns(session.Object);
            context.Expect(ctx => ctx.Server).Returns(server.Object);

            return context.Object;
        }

        public static HttpContextBase FakeHttpContext(string url)
        {
            HttpContextBase context = FakeHttpContext();
            context.Request.SetupRequestUrl(url);
            return context;
        }

        public static void SetFakeControllerContext(this Controller controller)
        {
            var httpContext = FakeHttpContext();
            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
        }

        static string GetUrlFileName(string url)
        {
            if (url.Contains("?"))
                return url.Substring(0, url.IndexOf("?"));
            else
                return url;
        }

        static NameValueCollection GetQueryStringParameters(string url)
        {
            if (url.Contains("?"))
            {
                NameValueCollection parameters = new NameValueCollection();

                string[] parts = url.Split("?".ToCharArray());
                string[] keys = parts[1].Split("&".ToCharArray());

                foreach (string key in keys)
                {
                    string[] part = key.Split("=".ToCharArray());
                    parameters.Add(part[0], part[1]);
                }

                return parameters;
            }
            else
            {
                return null;
            }
        }

        public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod)
        {
            Mock.Get(request)
                .Expect(req => req.HttpMethod)
                .Returns(httpMethod);
        }

        public static void SetupRequestUrl(this HttpRequestBase request, string url)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            if (!url.StartsWith("~/"))
                throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\".");

            var mock = Mock.Get(request);

            mock.Expect(req => req.QueryString)
                .Returns(GetQueryStringParameters(url));
            mock.Expect(req => req.AppRelativeCurrentExecutionFilePath)
                .Returns(GetUrlFileName(url));
            mock.Expect(req => req.PathInfo)
                .Returns(string.Empty);
        }
    }
}

对于 ASP.NET MVC 测试助手来说,另一个很好的资源是 CodePlex 上的 MvcContrib 项目.

Another good resource for ASP.NET MVC test helpers is the MvcContrib project on CodePlex.

在您拥有 FakeHttpContext 之后,您可以测试您的操作过滤器:

After you have a FakeHttpContext you can test your action filter:

var context = new ActionExecutedContext();
context.HttpContext = MvcMockHelpers.FakeHttpContext();
context.Result = new EmpytResult(); // or whatever the default result should be

var filter = new MyCustomAttribute();
filter.OnActionExecuted(context);

Assert.True(context.Result is EmpytResult);
...

这篇关于动作过滤器的 ASP.NET MVC 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆