views:

131

answers:

2

Hi

I’ve taken over an ASP.NET MVC project from a colleague. I have only a rudimentary knowledge of both ASP.NET MVC and unit testing.

I’m trying to get off on the right foot by creating unit tests. I thought I’d start with testing a controller. Unfortunately I stumbled at the first hurdle! The controller in question has the Authorize attribute and dependencies that are injected via dependency injection (Unity).

The controller looks something like:

namespace Project.Controllers
{
    [Authorize( Roles = "Admin,PurchaseOrderUser" )]
    public class SomeController : Controller
    {
        private readonly IOrganisationService _organisationService;
        private readonly IPurchaseOrderService _purchaseOrderService;

        // Dependency injection will provide these
        public SomeController(
            IPurchaseOrderService purchaseOrderService,
            IOrganisationService organisationService)
        {
            _purchaseOrderService = purchaseOrderService;
            _organisationService = organisationService;
        }

        // List Purchase Orders
        public ActionResult Index( )
        {
            Return View();
        }

        // Rest of controller....

So, using nUnit and Rhino Mock Mocks how can I test the Index action?

Thanks.

Alan T

+1  A: 

You should not care about the Authorize attribute as that is within the asp.net mvc framework and you have to assume that the framework is already tested. You just have to worry about the dependencies. That is pretty simple, as all you need to do is create mock instances of your dependencies and then instantiate a new controller with them. Something like this:

[Test]
public void TestMethod() {
    var organisationService = MockRepository.GenerateMock<IOrganisationService>();
    var purchaseOrderService = MockRepository.GenerateMock<IPurchaseOrderService>();
    //Setup your mocks
    var controller = new SomeController(organisationService, purchaseOrderService);
    var result = controller.Index();
    //Your asserts
}

You do not use your ioc container to inject dependencies in your tests.

Mattias Jakobsson
Thanks Mattias, I've give this a try.
Alan T
Mattias, I want to test that different users are given/not given access. You say leave it to the framework. Do we not need to unit test authorization?
Alan T
See Kennys answer for that.
Mattias Jakobsson
+2  A: 

You shouldn't test the attribute itself, rather you should test if the attribute is declared on the controller via reflection.

Think of it this way, if you implemented your own Authorize-attribute you should write tests to the attribute code too see that it worked. When you later used it on your controllers you've already tested the functionality of the attribute and just need to know if the controller is using it.

And the dependencies you create via your favorite Mock framework and inject as Mattias suggest.

Kenny Eliasson