How-to test action filters in ASP.NET MVC?

后端 未结 2 756
暗喜
暗喜 2020-12-13 11:20

Need some pointers for this. Found this and this, but I\'m still kind a confused.

I just want to mock ActionExecutedContext, pass it, let filter to work a bit and

2条回答
  •  长情又很酷
    2020-12-13 11:36

    This is the result:

    #region usages
    
    using System;
    using System.Collections.Specialized;
    using System.Web;
    using System.Web.Mvc;
    using x.TestBase;
    using x.UI.y.Infrastructure.Enums;
    using x.UI.y.Infrastructure.Filters;
    using x.UI.y.Test.Mocks;
    using Moq;
    
    //considering switch to NUnit... :D
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    #endregion
    
    namespace x.UI.y.Test.Unit.Infrastructure.Filters
    {
        [TestClass]
        public class RememberUrlTester : TesterBase
        {
            private static HttpContextBaseMock _context = 
                new HttpContextBaseMock();
            private static ActionExecutedContextMock _actionContext = 
                new ActionExecutedContextMock(_context.Object);
    
            [TestMethod]
            //"Can save url in session" (i prefer test names in my own language :)
            public void SpeejPieglabaatUrlSesijaa()
            {
                //Arrange
                const string _url = "http://www.foo.bar/foo?bar=bar";
                _context.RequestMock.SetUrl(_url);    
                var filter = new RememberUrlAttribute();
    
                //Act
                filter.OnActionExecuted(_actionContext.Object);
    
                //Assert
                _context.SessionMock.Verify
                    (m => m.Add(SessionKey.PreviousUrl.ToString(), _url));
            }
        }
    }
    

    Wrapped Mock to keep tests clean.

    I'm sure things can be done better, but I think it's a great start and I'm feeling quite excited.

    Finally that HttpContext monster is under control! ^^

提交回复
热议问题