Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test an ActionFilter in ASP.NET MVC?

There is an ActionFilter on my controller-class. The OnActionExecuting method gets called, when an action of the controller is called in a web application.

Now I call the Action in a UnitTest:

    NiceController niceController = new NiceController();
    ActionResult result = niceController.WhateverAction();

Is there a way to have the ActionFilter called?

like image 431
Mathias F Avatar asked Mar 04 '09 10:03

Mathias F


1 Answers

In order to have the ActionFilter called automatically, you are going to need to run the controller action invoker. This is possible, but it means that the MVC framework will try and execute the result. This means that you would have to use mocks to stub out the execution of the result. Again, that is possible, but it means that your unit test is becoming more mocks than actual code. It may be more correct to just test the filter directly. After all, the fact that OnActionExecuting is called is a feature of the framework, and you don't need to unit test the framework itself.

But I think that what you're really saying is that you want to test WhateverAction, and that action cannot work unless the ActionFilter has executed.

First, I would ask questions about this design. Is this correct? It might be. It is reasonable, for example, that an action with the Authorize attribute could presume that when it executes there is a logged in user. Of course, the action should test this, but the presumption is safe. On the other hand, actions should probably not require filters to do action-specific initialization. So you should ask the question, but the answer they well be that the design is correct.

In this case, the best decision for a unit test might be to manually execute the filter in the unit test, and to write a separate unit test which proves that the action is decorated with the correct attribute.

like image 67
Craig Stuntz Avatar answered Sep 22 '22 13:09

Craig Stuntz