Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 329
Arnis Lapsa Avatar asked Jun 29 '09 11:06

Arnis Lapsa


People also ask

How do you test a Action filter?

To unit test an action filter, you have to pass in an action filter context object (which requires a lot of setup). Action filter methods are void, so you have to verify the behavior by inspecting the context object (or dependencies, like a logger, if you are injecting those).

How many action filters are there in MVC?

I know , in ASP.Net MVC there are 4 filters i.e. AuthorizeFilter, ActionFilter, ResultFilter and ExceptionFilter.


1 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 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
like image 127
eu-ge-ne Avatar answered Oct 07 '22 17:10

eu-ge-ne