Archive for category Testing
Asp.net MVC: Testing a custom Authorize filters
Posted by Dario in Asp.Net MVC, Testing, Web on May 23rd, 2009
Asp.net MVC let you intercept the actions via a feature they call: Filters. Filters are just attributes that you decorate into actions and them allow to you make an stop before or after the action-methods are executed (also are filters to intercept code before/after the result is executed, errors are thrown, etc). There are a few kind of Filter attributes, in the picture bellow into the blue square you’ve what filters came supported out-of-the-box.

Today we are going to talk about the AuthorizeAttribute and how to extend and test it.
AuthorizeAttribute (from the Msdn):
Represents an attribute that is used to restrict access by callers to an action method.
This filter is the first to be called when the Controller Action Invoker try to run Action methods. You can set into the attribute which are the Users or Roles can execute an Action, if the User/Role doesn?t fulfill with what was established into the Action an Unauthorized Result is raised. Remember that exactly after the filter execution ended in a ActionResult, that result is executed.
Now, let?s go to the hypothetical scenario that you need a custom authorization schema, that you need more than User/Role, or you just need neither of both, because your model is based on a Security Level. So you don?t care about who is the guy? / or what role it has?, you just need the security level it has.
With this scenario you can write a custom Authorize attribute:
In this CustomAuthorize attribute, we are doing first the well known authorization (which is, executing the code as is in the class base). When that authorization part passed, we go through our custom authorization part: we get the user from the Database (or whatever other source) and we check the security level. If it?s allowed to execute the action-method we end without setting the result. If it?s not, we set a HttpUnauthorizedResult. In the browser you will be redirected to the login page if you?re not allowed to execute that code.
Now the problem is when you need to test the authorization. Actually you can do it with some mock and overriding some code.
Another thing you?ve to know is that the object in charge of execute the actions is the ControllerActionInvoker. Then to invoke and action into your tests and see the result when the filters are invoked, we need to customize some, and override the method in charge of execute the result (the ActionResult), which is InvokeActionResult. Where is how should looks our method override:
Assert is a class from a Unit Testing framework, in this case in the example is using the Unit Testing framework that came with Visual Studio because every user can run the tests without have ie: Resharper installed. This Assert is expecting that the Result from the filter/action execution is the same with the TResult (is a generic parameter declared into the class). So with this class, we can make an easy test to see if the result is authorized or unauthorized.
Our test for authorized access, should be looking like this
First we are creating a new Controller, we mock stuff for authentication, and then using our custom action invoker to try to invoke the action using InvokeAction method (passing the Context and the Action name to be executed).
We are using some extensions and helpers methods, i.e.: SetFakeAuthenticatedContext is included into the example and there you?ll see which elements you need to mock when use Authorize filter-attributes.
To understand what happened in this first test method:
- Controller creation
- Mock authentication stuff using our user named:?pepe?.
- Using the custom invoker we launch the action ?PermisiveAction?.
- The CustomAuthorized filter is raised, it pass the authorization.
- The action is executed and return a ViewResult (doing return View() into the code).
- The Assertion is made, everything ok and the test pass.
And now let?s see this another test
The difference with the previous one is in the step 4, 5 and 6. The action is not executed because the filter raise an HttpUnauthorizedResult. Download the example to understand better how to manage the testing of Authorization on Actions.
Download code example
XUnit 1.0.2 and Resharper 4.1
XUnit doesn’t support yet to run tests on Resharper 4.1 so I decided to build a home-made release.
You can download this XUnit package tested with Resharper 4.1 and with TestDriven 2.14.2190. This is not an official release, you can get the official one in the Codeplex page,use at your risk:
Download
XUnit 1.0 – Using ReSharper as Runner
Today I heard about this drop, that actually I was waiting for it. Time ago when this brand new project was release, we talked about it(Spanish post).
We have to remember that exist many Unit Testing frameworks, and XUnit is an special one, has many distinctive differences respect another frameworks like NUnit. Although the creator of XUnit is the same whom create NUnit, these projects are quite different. The main idea that led to creation of another new Unit testing framework for .Net was to leave some aspect that NUnit had strongly inherited from they source of inspiration: JUnit.
To run the tests with XUnit we can use different runners:
- xunit.console (included at XUnit’s binaries)
- xunit.gui (included at XUnit’s binaries)
- TestDriven (integrates with Visual Studio)
- Resharper 3.1 (integrates with Visual Studio)
Here you can see XUnit in action running into Resharper:

Rhino Mocks Syntax
Rhino Mocks it’s an excelent framework for mocking to use in our unit testings. One reason to use it is that do not make use of strings to hardcoding the names of types, methods, properties, etc, reducing the error posibilities at runtime.
After of 3.0.5 version released some time ago, the sintax became more easier to read and with less probabilities on errors.
At look this introductory screencast you’ll see how to do a typical mocking, and using the standart way to do it. The posibilities to forget the call VerifyCall() method exists.
[Test]
public void SigmoidalFunctionDerivative()
{
INet net = Mock<INet>();
ITransferFunction tf = new SigmoidalTransferFuncion();
Expect
.Call(net.Value)
.Return(5.0);
Mocks.ReplayAll();
//f'(net) = y * ( 1 - y )
Assert.Equal(0.006648057, Math.Round(tf.Derivate(net), 9));
Mocks.VerifyAll();
}
One way to do it more crearly and safety:
[Test]
public void SigmoidalFunctionDerivative()
{
INet net = Mock<INet>();
ITransferFunction tf = new SigmoidalTransferFuncion();
using (Mocks.Record())
{
Expect
.Call(net.Value)
.Return(5.0);
}
using (Mocks.Playback())
{
//f'(net) = y * ( 1 - y )
Assert.Equal(0.006648057, Math.Round(tf.Derivate(net), 9));
}
}
On this examples I’m using a helper for the Mock<T>() method and the MockRepository Mocks {get;set;}. Nothing unusual so far.
[Test]
public void SigmoidalFunctionDerivative()
{
INet net = Mock<INet>();
ITransferFunction tf = new SigmoidalTransferFuncion();
using (Mocks.Record())
{
Expect
.Call(net.Value)
.Return(5.0);
}
using (Mocks.Playback())
{
//f'(net) = y * ( 1 - y )
Assert.Equal(0.006648057, Math.Round(tf.Derivate(net), 9));
}
}
There is another way to do the same but using delegates instead of keyword using: The With class (actually I think that I know where it come from).
[Test]
public void SigmoidalFunctionDerivative()
{
INet net = Mock<INet>();
ITransferFunction tf = new SigmoidalTransferFuncion();
With
.Mocks(Mocks)
.Expecting(delegate
{
Expect
.Call(net.Value)
.Return(5.0);
})
.Verify(delegate
{
//f'(net) = y * ( 1 - y )
Assert.Equal(0.006648057,
Math.Round(tf.Derivate(net), 9));
});
}
I prefer the 2nd option.