Test Your IoC Container

There are doubts about if you should test registrations in you IoC container. I have been intimidated by this blog-post for a while and did not touch container for writing our tests. However, we did have a problem in the past, when DI container could not create one of our controllers. And we have lost days trying to chase the problem – there was no meaningful error message, because the real exception was swallowed somewhere in transit. It turned out that we have violated DI principal of a simple constructor: “Do nothing in constructor”. I have blogged about this before.

Today I would like to show how we test our IoC container to check if it can create all our controllers. Because controllers are immediate aggregate roots that are used by an end user. And controllers in MVC are the final consumer in the dependency chain. So if you likely to hit a problem in a chain of dependencies, it is likely that you will catch it by creating all the controllers.

Of course, if you use IoC container as a service locator or Mediator pattern you will have to test container separately for the types you get out from container there (mostly Command Handlers and Query Handlers).

Continue reading

Faking HTTP Context for your unit tests

While writing and testing ASP.Net MVC application, many times over I needed to simulate HTTP Request and presence of HttpContext.Current. I need this mostly when I try to test code that interacts with MVC framework, like MVC Action Filters or custom Model Binders or testing routes.

ASP.Net MVC 4 is quite good in this matter – most of the framework can be replaced by a mocked object and there is a minimum number of static calls or sealed objects. So you can do the HTTP Simulation, but usually it involves a lot of boiler-plate code and many mock-objects to be set-up.

Continue reading

How to test code for accessing Azure Storage REST Api

Update: There is an updated implementation of this code: see this blog post

One of my applications has a feature where it is given a URL with Shared Access Signature to Azure Blob Storage and then via REST API it uploads files to the storage. You can do that by provided Azure Storage libraries. Originally I had that functionality implemented with these libraries. But now I’m slimming down the application (this is a small command line app) and getting rid of unnecessary dependencies. And for the sake of one upload method I don’t want to tie myself to masses of extra DLLs. So I’m replacing the libraries with REST API call.

I have spent some time trying to test this functionality. You may say that this is a not a unit test. Yes, it is not a unit test. Other questions? Also you may say that you shouldn’t test these kind of things and wrap a class around these and ignore. That is what I have done in the past, but that particular piece of code caused an endless pain because I’ve done it all wrong and it was not covered by tests.

Continue reading

Constructor strategies for AutoFixture

For my unit tests I’m using an awesome tool Autofixture as data generator and as an Automocking container. But by default for creation of objects it uses the constructor with least number of arguments. Mark Seemann talks about this in his blog. Also he provides code on how to make Autofixture work the opposite way. But the code example in that blog post is outdated and no longer valid in the latest version of the framework.

So every time I need this (and this is not often) I have too search for the solution over-again. And just to save myself this research next time, I’ll put the solution here:

var fixture = new Fixture();

fixture.Customizations.Add(new MethodInvoker(new GreedyConstructorQuery()));

Test project per production project vs. Single project for all tests

For the last 7-8 months we have rolled a test project per production project. And it worked just fine when we started it. But over this weekend I have collapsed all test projects into one because many test project became a headache. And here are my reasons:

  1. The more projects you have in your Visual Studio solution, the slower VS is. I don’t know why that is, but for half-day I have tried excluding all extra projects and trying working with VS and it was much more snappier and happier. And we had 13 projects in our solution with total number of lines just above 133K (not including JS and HTML). And VS memory consumption have reduced in half when I went from 13 to 5 projects – that also made my PC happier.
  2. Package management on one test project takes 10 times less than on 6 projects. Every time you get new version of Moq, you need to update all your test projects. Or just one.
  3. Every time your production project gets a new dependency, you need to add that to your test projects. Or just one project.
  4. Did I tell you, dependency management gets 10 times easier with single test project?
  5. Less projects => less maintenance costs. And you don’t want to maintain test projects.

And what is the point of having a test project per project? Please somebody tell me! I have started that because I read that in books. Well, the books are wrong! There is no benefit of having test-project-per-project. Only headaches and slow Visual Studio.

Test your constructors to be simple

In the previous blog post I wrote how it is important to have a simple constructor that only accepts dependencies. And violation of this rule cost me at least 12 hours of debugging and blocking issue for some developers in the team. Now I have a unit test to prevent this kind of problem in the future.

One of the suggestions in the comments was to use strict mocks and inject them into a controller. And don’t set up any kind of expectations on mocks. This way if dependencies are doing anything in the controller, they will fail the test.

Continue reading

Ignore test categories in TFS build server using DefaultTemplate.xaml

At the moment I’m using excellent service from Microsoft: hosted TFS. The service is still in the preview (15 July 2013) and some features are in beta, but it works pretty smoothly already. One of the things I had to learn is how to use TFS as a build server. I’ve used to nice TeamCity with almost drag-and-drop build steps and simple configuration management. TFS is using XAML definition file to drive the build process. The default template that comes with any project is pretty much covers everything you might need when you start, but it is very complex and when you try looking on the XAML diagram, you might want to run away – it’s that big and complex. That’s what I did first time I looked on the XAML processes. Run away and installed TeamCity.

Now I’ve decided to give it another go. I’ve started from enabling nUnit tests on build server. By default TFS only works with MSTest. To enable nUnit, you need to add nUnit assemblies and nUnit to MSTest adapter to your source control. The process is perfectly described in this post by Ajay Majgaonkar. I’ve also seen the description of the process in some Microsoft documentation, but have lost the link.

Continue reading

Mocking Dependency Injection.

All the cool kids do write their own dependency injection container at some point. Today I had to come up with one for testing purposes:

public class MockDependencyResolver : IDependencyResolver
{
    private readonly Dictionary<Type, object> collection;

    public MockDependencyResolver()
    {
        collection = new Dictionary<Type, object>();
    }

    public void Freeze<T>(object mockedObject)
    {
        collection.Add(typeof(T), mockedObject);
    }

    public object GetService(Type serviceType)
    {
        if (collection.ContainsKey(serviceType))
        {
            return collection[serviceType];
        }
        var message = String.Format("No object is registered for type {0}", serviceType.Name);
        throw new ArgumentException(message);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        throw new NotImplementedException();
    }

Pretty simple, really. Very simple. And here how I use it in tests:

[TestFixture]
public class SomeClassTests
{
    private MockDependencyResolver dependencyResolver;

    public void Initialize_GenericInstance_IsValid(String forkName)
    {
        var dependencyResolver = new MockDependencyResolver();

        // this is a part of MVC project, hence MVC internal static reference
        System.Web.MVC.DependencyResolver.SetResolver(dependencyResolver);

        // I'm using Moq framework
        var someService = new Mock<ISomeService>();
        dependencyResolver.Freeze<ISomeService>(someService.Object);
        someService.Setup(c => c.SomeDepenentOperation()).Verifiable();

        // do you tests with someService as a dependency
        // inside of the class under test somewhere I have 
        //  DependencyResolver.Current.GetService<ISomeService>(); that would return null
        //  without mocking of DI

        someService.VerifyAll();
    }
}

Autofixture and Moq to test Entity Framework project

In the past month I have been using brilliant tool from Mark Seemann called Autofixture. The tool is aiming unit tests and shall help you create objects with some data filled in.

Usually for unit tests you need to create your objects manually and give them some kind of data inside of the objects, so you don’t get NullReferenceExceptions. And that sometimes takes a while and not always pleasant:

        var person = new Person
        {
            FirstName = "Dilbert",
            MiddleName = "Wall-E",
            Surname = "Smith",
            KnownAs = "Pointy Haired Boss",
            DateOfBirth = new DateTime(1975, 12, 31),
            Gender = Gender.Male,
            MaritalStatus = MaritalStatus.Single,
        };

Continue reading

Rollback attribute for NUnit and Entity framework

For integration testing it is very useful to wrap the tests in database transaction, and at the end of the test you just rollback the transaction, so any changes happened inside of the test are not persisted. And the next test run will be running on untouched data.

This is how the attribute looks:

using System;
using System.Transactions;
using NUnit.Framework;

/// <summary>
/// Rollback Attribute wraps test execution into a transaction and cancels the transaction once the test is finished.
/// You can use this attribute on single test methods or test classes/suites
/// </summary>
public class RollbackAttribute : Attribute, ITestAction
{
    private TransactionScope transaction;

    public void BeforeTest(TestDetails testDetails)
    {
        transaction = new TransactionScope();
    }

    public void AfterTest(TestDetails testDetails)
    {
        transaction.Dispose();
    }

    public ActionTargets Targets
    {
        get { return ActionTargets.Test; }
    }
}

Nothing fancy, just used NUnit’s ability to create custom attributes.

The tests will look like

[Test, Rollback]
public void YourTest() {
    // test method body
}

Alternatively you can apply Rollback attribute on the test suite and every test will be wrapped into a transaction automatically. Save you littering Rollback attribute on all the test methods.

[TestFixture, Rollback]
public class ClassUnderTestTests{
   // Test methods
}

Enjoy!