Testing roles in Authorize attribute on a ASP.NET Web API Controller

Recently at work we had to restrict access to a ASP.NET Web API Controller to users in two specific Active Directory groups.  We also wanted to create a test that verified this change and I thought it would be nice to share the approach we took to add some coverage.

The Employee Controller

[Authorize(Roles = @"MYDOMAIN\HR,MYDOMAIN\Admin")]
public class EmployeeController : ApiController
{
....

}

The Test

The test we came up with used reflection and ensured that the expected roles were set-up to be authorized.

    [TestFixture]
    public class EmployeeControllerShould
    {
        [TestCase(@"MYDOMAIN\HR")]
        [TestCase(@"MYDOMAIN\Admin")]
        public void Authorize_for_users_in_role(string role)
        {
            var controllerType = typeof(EmployeeController);
            var attribute = (AuthorizeAttribute)controllerType.GetCustomAttribute(typeof(AuthorizeAttribute), false);

            Assert.That(attribute.Roles, Is.StringContaining(role));
        }        
    }

NUnit & Moq – Setting a return value for a method call

Following on from my last post NUnit & Moq – Asserting a method is called I am now going to detail, in an example, how you can set-up a Mocked object to have a particular value returned when you execute a particular method on the Mocked object.

Program code

This is the main program code that you implement in a console app, if you wish to play around with this code before implementing it.

using PlayConsole.Processor;

namespace PlayConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var service = new CustomerService(new RetreiveCustomerQuery());
            var customerFullName = service.GetCustomerFullName(1);          
        }
    }
}

IRetreiveCustomerQuery Interface code

This is the interface for the database query class that we will be Mocking in our test so that it returns a known Customer object when the CustomerService’s GetCustomerFullName() method executes the query class’s Run() method.

namespace PlayConsole.Processor
{
    public interface IRetreiveCustomerQuery
    {
        Customer Run(int id);
    }
}

Retreive Customer Query implementation code

This is the implementation for the IRetreiveCustomerQuery interface.

namespace PlayConsole.Processor
{
    public class RetreiveCustomerQuery : IRetreiveCustomerQuery
    {
        public Customer Run(int id)
        {
            //Some code could be here to query database for this data
            return new Customer { Id = id, FirstName = "Fred", LastName = "Bloggs" };
        }
    }
}

CustomerService code

This is the service code. Later in our test class we will be verifying that it’s GetCustomerFullName() method returns the expected FullName of the given Customer. We are testing this by seting up a Mocked instance of IRetreiveCustomerQuery and having it return a know Customer object when it’s Run() method is executed.

namespace PlayConsole.Processor
{
    public class CustomerService
    {
        private readonly IRetreiveCustomerQuery _query;
        public CustomerService(IRetreiveCustomerQuery query)
        {
            _query = query;
        }
        public string GetCustomerFullName(int id)
        {
            var customer = _query.Run(id);
            return string.Format("{0} {1}", customer.FirstName, customer.LastName);
        }
    }
}

CustomerServiceTests

This test class is where you can see the Mocking in place. You will see that a known Customer object is returned when the Run() method is called on the Mocked Object Mock<IRetreiveCustomerQuery. You can also see that we can then assert that the expected full name for the customer is returned when executing the GetCustomerFullName() method on CustomerService.

using Moq;
using NUnit.Framework;
using PlayConsole.Processor;

namespace PlayConsoleUnitTests.Processor
{
    [TestFixture]
    public class CustomerServiceTests
    {
        private Mock _query;
        private CustomerService _service;
        private readonly Customer _customer = new Customer
        {
            Id = 1,
            FirstName = "John",
            LastName = "Jones"
        };

        [SetUp]
        public void Setup()
        {
            _query = new Mock();

            _query.Setup(x => x.Run(It.IsAny()))
                  .Returns(_customer);

            _service = new CustomerService(_query.Object);
        }

        [Test]
        public void Succesfully_retreive_customers_fullname()
        {
            var fullName = _service.GetCustomerFullName(1);
            var expectedFullName = string.Format("{0} {1}", _customer.FirstName, _customer.LastName);
            Assert.That(fullName, Is.EqualTo(expectedFullName));
        }

    }
}

NUnit & Moq – Asserting a method is called

Some people can find using a Mocking framework when writing unit tests tricky when they first start to do this so I thought I’d create some posts with examples.  I will be using Moq and NUnit. You can find the version of Moq I am using on NuGet

In this post I will show how to create a Mock and then assert that a method is called on the Mock.

Program code

This is the main program code that you implement in a console app if you wish to play around with this code before implementing it.

using PlayConsole.Processor;

namespace PlayConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var processor = new MyProcessor(new LogWriter());
            processor.Start();                
        }
    }
}

ILogWrite Interface code

This is the interface for the log writer that we will be verifying in our test that it’s write method is called by MyProcessor’s Start() method.

namespace PlayConsole.Processor
{
    public interface ILogWriter
    {
        void Write();
    }
}

LogWriter implementation code

This is the implementation for the log writer.

using System;

namespace PlayConsole.Processor
{
    public class LogWriter : ILogWriter
    {
        public void Write(string message)
        {
            Console.WriteLine(message);
        }
    }
}

MyProcessor code

This is the processor code. Later in our test class we will be verifying that it’s Start() method calls the Write() method on it’s implementation of ILogWriter

using System;

namespace PlayConsole.Processor
{
    public class MyProcessor
    {
        private readonly ILogWriter _writer;
        
        public MyProcessor(ILogWriter writer)
        {
            _writer = writer;
        }

        public void Start()
        {
            _writer.Write("Processor has started");
            Console.WriteLine("Hello World");
        }
    }
}

MyProcessorTests

This test class is where you can see the Mocking in place. The simple test verifies that the Write() method is called on ILogWriter once when the Start() method on MyProcessor is executed.

using Moq;
using NUnit.Framework;
using PlayConsole.Processor;
 
namespace PlayConsoleUnitTests.Processor
{
    [TestFixture]
    public class MyProcessorTests
    {
        private MyProcessor _processor;
        private Mock<ILogWriter> _writer;
 
        [SetUp]
        public void Setup()
        {
            _writer = new Mock<ILogWriter>();
            _writer.Setup(x => x.Write(It.IsAny<string>()));
            _processor = new MyProcessor(_writer.Object);
        }
 
        [Test]
        public void Succesfully_write_to_log()
        {
            _processor.Start();
            _writer.Verify(x => x.Write("Processor has started"), Times.Once());
        }
    }
}