How to check action filters in ASP.NET MVC?

This requires some pointers. Found this one and this one , but I'm still confused.

I just want to mock the ActionExecutedContext, pass it on, let the filter work a bit and check the result.

Any help?

You can find the filter source here.
(it has changed a little, but that is not the point at the moment).

So, I want to unit test that the RememberUrl filter is smart enough to keep the current URL in the session.

+14
asp.net-mvc testing action-filter
Jun 29 '09 at 11:14
source share
2 answers

1) Mocking Request.Url in ActionExecutedContext:

var request = new Mock<HttpRequestBase>(); request.SetupGet(r => r.HttpMethod).Returns("GET"); request.SetupGet(r => r.Url).Returns(new Uri("http://somesite/action")); var httpContext = new Mock<HttpContextBase>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); var actionExecutedContext = new Mock<ActionExecutedContext>(); actionExecutedContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object); 

2) Suppose you insert a session wrapper into your public RememberUrlAttribute constructor.

 var rememberUrl = new RememberUrlAttribute(yourSessionWrapper); rememberUrl.OnActionExecuted(actionExecutedContext.Object); // Then check what is in your SessionWrapper 
+11
Jun 29 '09 at 12:42
source share

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 <HttpWhatever> to keep the tests clean.

I am sure that everything can be done better, but I think this is a great start, and I feel very excited.

Finally, the HttpContext monster is in control! ^^

+3
Jun 29 '09 at 23:52
source share



All Articles