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));
        }        
    }

Write code that is easy to read – Clean Code Post 4

Writing code is relatively easy, but reading it can be hard if care has not been taken by the Author of the code. Taking the time to write clean code pays off as you are not just making your live easier, if you have to revisit code, but you are also making future readers of your code lives easier too.

Writing sloppy code injects technical debt into your code base and as you may know technical debt is depressing. Technical debt de-motivates people and will potentially drive people away from your organisation.

Being sloppy slows you down in the long run as your code is likely to have bugs and need tidying up in the future.

One thing you can do to improve the quality of you code you are writing is to follow the TED rule:

Terse
Your code should not be excessively wordy

Expressive:
It is clear what your code is trying to do

Do one thing
Your code should have a clear responsibility. It should do that one thing well

Make use of Enums – Clean Code Post 3

It is better to make use of an Enum than to use hardcoded strings in your code. I have heard the use of hardcoded strings be referred to as Stringly Typed rather than Strongly Typed. Using an Enum would make your code Strongly Typed.

Here is an example of some bad Stringly Typed code:

if (customerType == "Premier")
{
                
}

Here is an example of how you can improve this code by making use of an Enum called CustomerType:

if (customer.Type == CustomerType.Premier)
{
               
}

The code to define the CustomerType Enum is below.

public enum CustomerType
{
   Standard, Elevated, Premier
}

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. In the CustomerType enumeration above, Standard is 0, Elevated is 1 and Premier is 2. If you wanted to assign different values you can do something like the code below:

public enum CustomerType
{
   Standard = 100, 
   Elevated = 200, 
   Premier = 300
}

If you want to retrieve the integral value from an Enum you can use the code below:

   var customerType = (int)customer.Type;

Make use of Ternary (Conditional) Operator – Clean Code Post 2

It is more elegant in code to use the Ternary Operator than an IF statement. The Ternary Operator is also commonly known as the Conditional Operator.

Here is a C# example of a Ternary Operator in use:

int bonus = employee.Age < 50 ? 20 : 40;

You can see that it takes up less lines of code then the IF statement below:

int bonus;

if (employee.Age < 50)
{
  bonus = 20;
}
else
{
  bonus = 50;
}

You can see that it is much cleaner to use the Ternary Operator and results in using one line of code rather than ten.

Writing Clean Code

I recently watched a very good course on Pluralsight on writing Clean Code.  It is called Clean Code: Writing Code for Humans and is authored by Cory House.  I highly recommend it if you are lucky to have a Pluralsight subscription.

After watching the course I thought it would be good to write a few posts on writing Clean Code, which is what I plan to do over the coming weeks.  I will be including some tips I have picked up over the years.

Other Resources
There are various other resources already available on writing clean code and on how to improve as a Software Engineer.

Robert C Martin (Uncle Bob) has a collection of videos that you can pay to watch on Clean Code on the website https://cleancoders.com.

Below are a few books that are also well known in the industry

  • Clean code by Robert C Martin (Uncle Bob)
  • Code complete by Steve McConnell
  • The pragmatic programmer by Andrew Hunt and David Thomas

If you are reading this and have any other suggestions please feel free to leave a comment with the details.

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());
        }
    }
}

Obtain the namespace for either a Class or an Object

This post is just a reminder for me.  It’s not anything complex.  I had to write some code today to get the namespace as a string for a specific class and thought I would put it somewhere for quick reference.   I will include an example of obtaining the namespace for an object that is initialized for completeness.

  1. Example C# code to obtain namespace for a specific Class:

    var theNamespace = typeof(MyClass).Namespace
  2. Example C# code to obtain the namespace for an initialized Object:

    var myObject = new MyClass();
    var theNamespace = myObject.GetType().Namespace;

Pluralsight – online training courses for software developers

I’ve been meaning to post this for a while. I have signed up to Pluralsight.com and wanted to say how great I think it is!

I have watched the two C# Fundamentals courses to refresh myself and am now watching the WCF Fundamentals course ahead of taking the MCTS exam Windows Communication Foundation Development with Microsoft .NET Framework 4 on Wednesday.

I think I am hooked so will publish any other courses I watch that are any good.  If you are reading this and can recommend some please do!  Or if you use an alternate on-line training course website then also let me know.