Dependency Injection and highly coupled objects

power-plugI consider that Dependency Injection (DI) is a very helpful pattern, I love to use it in order to reduce the coupling in my code and it helps me when writing unit tests. But sometimes the code depends on objects that are difficult or impossible to mock.

The HttpContext class of the ASP .NET MVC framework is one example of this kind of object.

I created the following Controller and View as examples:

public class IndexController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        string[] languages = HttpContext.Request.UserLanguages;
        return View(model:languages);
    }
}
@model string[]
@{
    Layout = null;
}
 
<!--DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        @foreach (string language in Model)
        {
            @language
            <br/>
        }
    </div>
</body>
</html>

This view displays the languages preferences from the request for the visitor:

languages-preferences

Now, I want to test my Controller (even if there is no logic in my example) with the following code:

[TestClass]
public class IndexControllerTest
{
    [TestMethod]
    public void IndexActionTest()
    {
        IndexController controller = new IndexController();
        ViewResult view = controller.Index() as ViewResult;
        Assert.IsNotNull(view);
    }
}

I just want to check that the view is not null but the test fails. I get a NullReferenceException because the HttpContext property of the Controller is null. This happens because there is no web context when executing the test and it makes sense since the execution occurred in a test context.

The first thing that comes to mind to fix this issue is to set the HttpContext property with a mock. But I cannot do that because this property is read only and thus I am not able to set it when doing the instantiation of the controller in the test method.

And if you need to mock the HttpContext class, you cannot because it is sealed. To avoid this you can use the HttpContextBase abstract class instead but in a test environment you will have to implement it in order to mock it and you don’t want to do this. Why? Because it’s a pain to do, you will have to provide implementation for everything, it’s like creating an entire web context just for the test. And in my case I just need the user languages.

So? What now? Do we give up testing our controllers? Absolutely not, it is possible to achieve our goal without too much complications. From the beginning I tried to mock the wrong thing. What I need is the user languages not the HttpContext, so let’s remove this dependency. I created the following interface with the data my code will use:

public interface IWebContext
{
    string[] UserLanguages { get; }
}

And now I will inject this interface in my Controller and I will create a specific implementation that will use the HttpContext to retrieve the languages from the request:

public class RealContext : IWebContext
{
    private HttpContext _context;
 
    public RealContext(HttpContext context)
    {
        _context = context;
    }
 
    public string[] UserLanguages
    {
        get { return _context.Request.UserLanguages; }
    }
}
 
public class IndexController : Controller
{
    IWebContext _context;
 
    public IndexController()
        : this(new RealContext(System.Web.HttpContext.Current)) { }
 
    public IndexController(IWebContext context)
    {
        _context = context;
    }
 
    [HttpGet]
    public ActionResult Index()
    {
        string[] languages = _context.UserLanguages;
        return View(model:languages);
    }
}

Note that I created a parameters-less constructor that instantiate the dependency, without this constructor the ASP .NET MVC will not be able to create the Controller (it won’t even compile).

I can now update my test by using a mock for my interface:

public class MockContext : IWebContext
{
    public string[] UserLanguages
    {
        get { return new string[1]; }
    }
}
 
[TestClass]
public class IndexControllerTest
{
    [TestMethod]
    public void IndexActionTest()
    {
        IndexController controller = new IndexController(new MockContext());
        ViewResult view = controller.Index() as ViewResult;
        Assert.IsNotNull(view);
    }
}

My test is now passing! I removed the dependency between the test and the web context objects, I can now test the logic of my controller without having to set up an awful lot of mocks.

I encapsulated my specific logic inside an abstraction that is far easier to mock. This way I was able to reduced the coupling, I was also able to increase my code coverage and all of it without losing any behavior.

You can use this technique for other properties of the HttpContext like the user agent if you want to apply some logic on it and test it. Or also for static classes/methods (that you can maybe found in your legacy code).

I hope this will help you and as usual do not hesitate to leave a comment.

See you next time!

Extending mocking with Moq

simulator

In the last part of my Dependency Injection article I introduced the term of “mocking”. This kind of test double can be really powerful. Yet in my example I had to create 2 new classes (my mocks) to be able to test my functionality in order to reduced coupling. Here is the code used by the tests:

class MockNotifier : INotifier
{
    public MockNotifier()
    {
        NotifyHasBeenCalled = false;
    }
 
    public bool NotifyHasBeenCalled { get; private set; }
 
    public void Notify(User user)
    {
        NotifyHasBeenCalled = true;
    }
}
 
class MockRepository : IUserRepository
{
    public bool HasValidatedNotification { get; set; }
 
    public User GetById(int userId)
    {
        return new User { HasActivatedNotification = HasValidatedNotification };
    }
}
 
[TestClass]
public class NotificationServiceTest
{
    private NotificationService _notificationService;
    private MockNotifier _mockNotifier;
    private MockRepository _mockRepository;
 
    [TestInitialize]
    public void TestInit()
    {
        _mockNotifier = new MockNotifier();
        _mockRepository = new MockRepository();
        _notificationService = new NotificationService(_mockRepository, _mockNotifier);
    }
 
    [TestMethod]
    public void NotificationActivated()
    {
        _mockRepository.HasValidatedNotification = true;
        _notificationService.NotifyUser(1);
        Check.That(_mockNotifier.NotifyHasBeenCalled).IsTrue();
    }
 
    [TestMethod]
    public void NotificationDeactivated()
    {
        _mockRepository.HasValidatedNotification = false;
        _notificationService.NotifyUser(1);
        Check.That(_mockNotifier.NotifyHasBeenCalled).IsFalse();
    }
}

I think that being able to write its own mocks is a great exercise to understand Oriented Object Programming (OOP) in a testing context. But in a larger application it is likely that you will have an enormous amount of them, it is a lot of code to maintain. This is why I will introduce a mocking framework name Moq.

I used this nuget package for a few months now and it offers a lot of helpful functionalities. But I think that it can be a bit complex to use at first when people are not familiar with the mocking technique. Let’s see how the previous code can be refactored when using Moq:

[TestClass]
public class NotificationServiceTest
{
    private NotificationService _notificationService;
    private Mock<INotifier> _mockNotifier;
    private Mock<IUserRepository> _mockRepository;
 
    private User _fakeUser;
 
    [TestInitialize]
    public void TestInit()
    {
        _mockNotifier = new Mock<INotifier>();
        _mockRepository = new Mock<IUserRepository>();
        _notificationService = new NotificationService(_mockRepository.Object, _mockNotifier.Object);
        _fakeUser = new User();
 
        _mockRepository.Setup(m => m.GetById(It.IsAny<int>())).Returns(_fakeUser);
    }
 
    [TestMethod]
    public void NotificationActivated()
    {
        _fakeUser.HasActivatedNotification = true;
        _notificationService.NotifyUser(It.IsAny<int>());
        _mockNotifier.Verify(m => m.Notify(It.IsAny<User>()), Times.Once());
    }
 
    [TestMethod]
    public void NotificationDeactivated()
    {
        _fakeUser.HasActivatedNotification = false;
        _notificationService.NotifyUser(It.IsAny<int>());
        _mockNotifier.Verify(m => m.Notify(It.IsAny<User>()), Times.Never());
    }
}

First thing to be aware of is that the manipulated object are Mock instances and not implementations of the interfaces. It is possible to access these implementations by using the Object property of the Mock to inject the dependencies to a client object (NotificationService in this case). I also used the Setup method of the MockRepository to return a new instance of User when the GetById method is called.

Moq also provides a Verify method to check whether or not a method has been called and how many times. This is the method I used in the test to validate my test scenarios. You can notice that I no longer used NFluent, because in this case I don’t need it. Yet it is possible to use NFluent with Moq for the tests, they work really well together.

Last but not least, Moq provides powerful methods to match arguments, in my example it is the It.IsAny method. With this I can tell my Mock to accept any value as parameter because I am not testing it in my unit tests since it is irrelevant in this testing context.

This is just a quick overview of the possibilities offered by Moq and I encouraged you to check this awesome mocking framework.

See you next time !

Dependency Injection to the rescue

code-coupling

I am a developer, I believe in unit testing and I write a lot of them. But it was not always the case, mostly because I was working on a highly coupled code base. Whenever I wanted to test a single functionality I had to set up a lot of things (database, configuration files, …) to do so even if this functionality was not linked to these dependencies. It was spaghetti code into a big ball of mud.

Then I discovered the Dependency Injection (DI) pattern and it changed the way I designed my code and it made testing much easier. The DI purpose is to reduce coupling between software components in order to improve maintainability and testability. I created the following piece of code to demonstrate the principle :

public class User
{
    public string Name { get; set; }
    public string Email { get; set; }
    public bool HasActivatedNotification { get; set; }
}
 
public class EmailNotifier
{
    public void Notify(User user)
    {
        var message = string.Format("Hello {0} ...", user.Name);
        // Sending email
        // ...
    }
}
 
public class UserRepository
{
    public User GetById(int userId)
    {
        // Fetching information from datasource
        // ...
        return new User { Name = "John", Email = "john@john.com" };
    }
}
 
public class NotificationService
{
    public void NotifyUser(int userId)
    {
        var repository = new UserRepository();
        var user = repository.GetById(userId);
 
        if (user.HasActivatedNotification)
        {
            var notifier = new EmailNotifier();
            notifier.Notify(user);
        }
    }
}

The NotificationService sends an email to a given user if he has activated the notifications. Now if I want to test this logic I will have to set up a datasource for my repository and a mail inbox for the notifier. This is a lot of configuration for a simple piece of logic. This code is highly coupled because the NotifyUser method of my service instantiates its dependencies (the repository and the notifier), this means that the Single Responsibility Principle (SRP) is not respected. I will use the Constructor Injection technique to change the code :

public interface INotifier
{
    void Notify(User user);
}
 
public class EmailNotifier : INotifier
{
    public void Notify(User user)
    {
        var message = string.Format("Hello {0} ...", user.Name);
        // Sending email
        // ...
    }
}
 
public interface IUserRepository
{
    User GetById(int userId);
}
 
public class UserRepository : IUserRepository
{
    public User GetById(int userId)
    {
        // Fetching information from datasource
        // ...
        return new User { Name = "John", Email = "john@john.com" };
    }
}
 
public class NotificationService
{
    public NotificationService(IUserRepository repository, INotifier notifier)
    {
        _repository = repository;
        _notifier = notifier;
    }
 
    private readonly IUserRepository _repository;
    private readonly INotifier _notifier;
 
    public void NotifyUser(int userId)
    {
        var user = _repository.GetById(userId);
 
        if (user.HasActivatedNotification)
        {
            _notifier.Notify(user);
        }
    }
}

The UserRepository and the EmailNotifier are unchanged, they just implement interfaces. Now the NotificationService uses these interfaces as fields that are injected through the constructor. The NotifyUser method can now use these dependencies without having to create them, the code is “cleaner”.

I added interfaces for the repository and the notifier for testing purpose, I can test my service with a fake repository and a fake notifier that do not require heavy configuration :

class MockNotifier : INotifier
{
    public MockNotifier()
    {
        NotifyHasBeenCalled = false;
    }
 
    public bool NotifyHasBeenCalled { get; private set; }
 
    public void Notify(User user)
    {
        NotifyHasBeenCalled = true;
    }
}
 
class MockRepository : IUserRepository
{
    public bool HasValidatedNotification { get; set; }
 
    public User GetById(int userId)
    {
        return new User { HasActivatedNotification = HasValidatedNotification };
    }
}

These two implementations are mocks, it means that they mimic the behavior of concrete classes and are used only for testing purpose. In my MockNotifier I just set a flag to true when the Notify method is called, and the GetById method of the MockRepository returns a User instance with the wanted value for HasActivatedNotification. I created a test class with NFluent to show how it is used :

[TestClass]
public class NotificationServiceTest
{
    private NotificationService _notificationService;
    private MockNotifier _mockNotifier;
    private MockRepository _mockRepository;
 
    [TestInitialize]
    public void TestInit()
    {
        _mockNotifier = new MockNotifier();
        _mockRepository = new MockRepository();
        _notificationService = new NotificationService(_mockRepository, _mockNotifier);
    }
 
    [TestMethod]
    public void NotificationActivated()
    {
        _mockRepository.HasValidatedNotification = true;
        _notificationService.NotifyUser(1);
        Check.That(_mockNotifier.NotifyHasBeenCalled).IsTrue();
    }
 
    [TestMethod]
    public void NotificationDeactivated()
    {
        _mockRepository.HasValidatedNotification = false;
        _notificationService.NotifyUser(1);
        Check.That(_mockNotifier.NotifyHasBeenCalled).IsFalse();
    }
}

I can test the logic of my service without having to configure a datasource with pre-configured users and without checking in a inbox if there is an email or not. Dependency Injection reduces code coupling and makes testing easier even if you have to create dedicated classes for them. You can find more information about DI here and here.

Constructor Injection is a pattern I use because with it I improved the maintainability of my code base with less coupling and more testing, you should try it as well if it’s not the case.

See you next time !

Keep control of your entities

Today I want to share tips to improve the control you have over your code and especially over your entities in a Oriented Object language. The example will be in C# .NET.

During my (still short) career I’ve been  working on a certain amount of projects and I often found the same practices related to entities : they are just PODS !

Here’s an example with an Invoice, a Product and a Customer entities.

public class Product
{
    public UInt16 Id { get; set; }
    public string Name { get; set; }
}
 
public class Customer
{
    public string Name { get; set; }
}
 
public class Invoice
{
    public Product Product { get; set; }
    public Customer Customer { get; set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine("{0} ordered :", Customer.Name);
        Console.WriteLine("{0} - {1}", Product.Id, Product.Name);
    }
}

Now, let’s use these classes in a program :

class Program
{
    static void Main(string[] args)
    {
        Invoice invoice = new Invoice();
        invoice.DisplayInfo();
    }
}

And yes, this program throws a NullReferenceException when displaying the invoice because my Invoice.Customer instance is NULL. Let’s fix our Invoice class the following way.

public class Invoice
{
    public Invoice()
    {
        Product = new Product();
        Customer = new Customer();
    }
 
    public Product Product { get; set; }
    public Customer Customer { get; set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine("{0} ordered :", Customer.Name);
        Console.WriteLine("{0} - {1}", Product.Id, Product.Name);
    }
}

But this time the program class looks like this :

class Program
{
    static void Main(string[] args)
    {
        Invoice invoice = new Invoice();
        invoice.Customer = null;
        invoice.DisplayInfo();
    }
}

The NullReferenceException still occurs because the Customer is set to NULL. I know you wonder why I did this… Because the code structure allows me to do it ! It might look stupid this way but sometimes in a more complex application you can set an object’s property to NULL without knowing it, if you’re calling an external service for example or another provider.

Let’s change our Invoice class again to use a bit of encapsulation.

public class Invoice
{
    public Invoice(Product product, Customer customer)
    {
        Product = product;
        Customer = customer;
    }
 
    public Product Product { get; protected set; }
    public Customer Customer { get; protected set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine("{0} ordered :", Customer.Name);
        Console.WriteLine("{0} - {1}", Product.Id, Product.Name);
    }
}

With this version the Customer and the Product have to be set when constructing the Invoice. So ? Do you think we’re done ? Let’s find out with a new program.

class Program
{
    static void Main(string[] args)
    {
        Invoice invoice = new Invoice(null, null);
        invoice.DisplayInfo();
    }
}

Still not running correctly, still the same exception for the exact same reason. You can add control to your entities properties but you should add control during initialization as well to avoid manipulating an invalid instance of your class.

This lead us to our final version of the Invoice class (at least in this post).

public class Invoice
{
    public Invoice(Product product, Customer customer)
    {
        if (product == null)
            throw new ArgumentNullException("product");
        if (customer == null)
            throw new ArgumentNullException("customer");
 
        Product = product;
        Customer = customer;
    }
 
    public Product Product { get; protected set; }
    public Customer Customer { get; protected set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine("{0} ordered :", Customer.Name);
        Console.WriteLine("{0} - {1}", Product.Id, Product.Name);
    }
}

I choose to use the ArgumentNullException to prevent the construction of an invalid object. This allow me to have a complete control on my Invoice entity. With these kind of practices I try to prevent incorrect behavior from misuse. I transformed a PODS into an entity with “intelligence”.

I hope these tips will help you and do not hesitate to share yours and/or to comment about these tips.

See you next time for more software development related topics !