views:

168

answers:

2

Hi

I have my own custom Authorize Attribute and I am trying to check my controller methods to see if they have the correct roles in place. Now my custom authorize tag has database code in it.

The ways I am mocking it up don't seem to work since the reflection stuff I found seems to to just pass no arguments so my default constructor in the Authorize Attribute gets hit creating a new service layer object that creates a repository object(that kills the unit test).

 var indexAction = typeof(Controller).GetMethod(method);
        var authorizeAttributes = indexAction.GetCustomAttributes(typeof(AuthorizeAttribute), true);

        //Assert
        Assert.That(authorizeAttributes.Length > 0, Is.True);

        foreach (AuthorizeAttribute att in authorizeAttributes)
        {
            Assert.That(att.Roles, Is.EqualTo(roles));
        }

Constructors of my AutorizeAttribute

  public MyAuthorize()
    {
        authorize = new ServiceLayer();
    }

    public MyAuthorize(IServicelayer layer)
    {
        authorize = layer;
    }

the reflection stuff keeps calling my default constructor. How can I pass in a mock service layer or something?

Thanks

+1  A: 

Have you looked at some of the Mocking Frameworks? I've used these to fake the http context etc in the past.

Here's another Stack Overflow post that might be able to help you...

http://stackoverflow.com/questions/37359/what-c-mocking-framework-to-use

Chris Arnold
A: 

I don't think the problem is with your code but what you are trying to test. What determines the roles that the attribute has?

If you are retrieving the roles from your service layer based on something passed into the attribute, your tests should confirm that the attribute exists on the action it is protecting ( part of the controller tests ), the appropriate calls are made to your service layer from the attribute ( part of the attribute tests ), and that the service layer returns the appropriate values for a specific request ( part of the controller tests ).

To ensure all of the parts work together, you will need to use integration tests that essentially mimic the entire request pipeline - something like Steve Sanderson's MvcIntegrationTest should simplify this http://blog.codeville.net/2009/06/11/integration-testing-your-aspnet-mvc-application/

Neal