Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException thrown when testing custom AuthorizationAttribute

I have taken a look at:

  • How do I make a unit test to test a method that checks request headers?
  • How to mock Controller.User using moq
  • How do I unit test a controller method that has the [Authorize] attribute applied?

I am trying to test a custom AuthorizeAttribute that I wrote.

I have tried many different things to get it to work. This is my current attempt.

[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class ConfigurableAuthorizeAttribute : AuthorizeAttribute
{
    private Logger log = new Logger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private IRoleHelper roleHelper;

    public ConfigurableAuthorizeAttribute()            
    {
        roleHelper = new ADRoleHelper();
    }

    public ConfigurableAuthorizeAttribute(IRoleHelper roleHelper)            
    {
        this.roleHelper = roleHelper;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!httpContext.User.Identity.IsAuthenticated)
        {
            return false;
        }

        if (this.roleHelper.IsUserInRole(this.Roles, HttpContext.Current.User.Identity.Name))
        {
            return true;
        }

        return false;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        base.HandleUnauthorizedRequest(filterContext);
        filterContext.Result = new RedirectResult("~/home/Unauthorized");            
    }


}
[Test]
public void unauthenticated_user_not_allowed_to_access_resource()
{
    var user = new Mock<IPrincipal>();
    user.Setup(u => u.Identity.IsAuthenticated).Returns(false);

    var authContext = new Mock<AuthorizationContext>();
    authContext.Setup(ac => ac.HttpContext.User).Returns(user.Object);

    var configAtt = new ConfigurableAuthorizeAttribute();
    configAtt.OnAuthorization(authContext.Object);

    authContext.Verify(ac => ac.Result == It.Is<RedirectResult>(r => r.Url == ""));
}

No matter what I do I always get a System.NullReferenceException when I run the test. It never seems to get past the OnAuthorization call. The stack trace is as follows:

Result Message: System.NullReferenceException : Object reference not set to an instance of an object. Result StackTrace: at System.Web.Mvc.OutputCacheAttribute.GetChildActionFilterFinishCallback(ControllerContext controllerContext) at System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) at ...ConfigurableAuthorizeAttributeTests.unauthenticated_user_not_allowed_to_access_resource() in ...ConfigurableAuthorizeAttributeTests.cs:line 29

Does anybody have any ideas on how to solve this problem?

Edit

I found the solution. I also needed to mock ControllerDescriptor and make sure that HttpContextBase.Items returned a new Dictionary.

Working code:

var context = new Mock<HttpContextBase>();
context.Setup(c => c.Items).Returns(new Dictionary<object, object>());
context.Setup(c => c.User.Identity.IsAuthenticated).Returns(false);
var controller = new Mock<ControllerBase>();

var actionDescriptor = new Mock<ActionDescriptor>();
actionDescriptor.Setup(a => a.ActionName).Returns("Index");
var controllerDescriptor = new Mock<ControllerDescriptor>();            
actionDescriptor.Setup(a => a.ControllerDescriptor).Returns(controllerDescriptor.Object);

var controllerContext = new ControllerContext(context.Object, new RouteData(), controller.Object);
var filterContext = new AuthorizationContext(controllerContext, actionDescriptor.Object);
var att = new ConfigurableAuthorizeAttribute();

att.OnAuthorization(filterContext);

Assert.That(filterContext.Result, Is.InstanceOf<RedirectResult>());
Assert.That(((RedirectResult)filterContext.Result).Url, Is.EqualTo("~/home/Unauthorized"));
like image 238
pkidza Avatar asked Oct 11 '13 09:10

pkidza


People also ask

How do I resolve NullReferenceException?

You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does. For more information on declaring and initializing arrays, see Arrays and Arrays. You get a null return value from a method, and then call a method on the returned type.

How do I fix NullReferenceException in C#?

Solutions to fix the NullReferenceException To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. In the above example, if(cities == null) checks whether the cities object is null or not.

How do I fix NullReferenceException object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

What does NullReferenceException mean?

A NullReferenceException happens when you try to access a reference variable that isn't referencing any object. If a reference variable isn't referencing an object, then it'll be treated as null .


1 Answers

I found the solution. I also needed to mock ControllerDescriptor and make sure that HttpContextBase.Items returned a new Dictionary.

Working code:

var context = new Mock<HttpContextBase>();
context.Setup(c => c.Items).Returns(new Dictionary<object, object>());
context.Setup(c => c.User.Identity.IsAuthenticated).Returns(false);
var controller = new Mock<ControllerBase>();

var actionDescriptor = new Mock<ActionDescriptor>();
actionDescriptor.Setup(a => a.ActionName).Returns("Index");
var controllerDescriptor = new Mock<ControllerDescriptor>();            
actionDescriptor.Setup(a => a.ControllerDescriptor).Returns(controllerDescriptor.Object);

var controllerContext = new ControllerContext(context.Object, new RouteData(), controller.Object);
var filterContext = new AuthorizationContext(controllerContext, actionDescriptor.Object);
var att = new ConfigurableAuthorizeAttribute();

att.OnAuthorization(filterContext);

Assert.That(filterContext.Result, Is.InstanceOf<RedirectResult>());
Assert.That(((RedirectResult)filterContext.Result).Url, Is.EqualTo("~/home/Unauthorized"));
like image 142
pkidza Avatar answered Sep 30 '22 16:09

pkidza