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

Arnis Lapsa picture Arnis Lapsa · Jun 29, 2009 · Viewed 8.8k times · Source

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 check result.

Any help?

Source of filter you can find here
(it's changed a bit, but that's not a point at the moment).

So - i want unit test, that RememberUrl filter is smart enough to save current URL in session.

Answer

eu-ge-ne picture eu-ge-ne · Jun 29, 2009

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 are injecting session wrapper in your RememberUrlAttribute's public constructor.

var rememberUrl = new RememberUrlAttribute(yourSessionWrapper);

rememberUrl.OnActionExecuted(actionExecutedContext.Object);

// Then check what is in your SessionWrapper