Respect your test code #2: Create base classes for your test fixtures

When writing code, I often end up introducing a layer supertype – i.e. a base class with functionality shared by all implementations in that particular layer in my application.

This also holds for my test code – and why shouldn’t it? Test code is as real as real code, so the same rules apply and it should benefit from the same pain killers as we implement in our application code.

For example when testing repositories and services that need to query the database, I can save myself a lot of writing by stuffing all the boring NHibernate push-ups in a DbTestFixture supertype – this includes building a configuration that connects to a test database, building a session factory, storing that session factory somewhere, re-creating the entire database schema in the test fixture setup, and running each test in a transaction that is automatically rolled back at the end of each test + a few convenience methods that allow me to flush the current session etc.

The DbTestFixture might look something like this (note that all my repositories take an instance of ISessionProvider in their ctor – that’s how they obtain the currently ongoing session, which is why I have a TestSessionProvider to inject into repositories under test):

Then a fictional repository test might look as simple as this:

Note how DbTestFixture flushes in all the right places so I don’t need to worry about that.

This test fixture supertype can be used for all my database access tests, as well as integration testing. But what about unit tests? I am using Rhino Mocks, so my unit test fixture base looks like this:

Real simple – it just stores my MockRepository and gives me a few shortcuts to the mocks I care for. Then I inherit this further to ease testing e.g. my ASP.NET MVC controllers like this:

As you can see, I make it a real “fixture” – the controllers I am about to test will fit into this fixture like a glove, and I will certainly never forget to instantiate my controller only once, because I start out by implemeting that part in the implementation of the CreateController method.

A controller test might look like this:

Respect your test code #1: Hide object instantiation behind methods with meaningful names

One thing, that I find really annoying, is that somehow it seems to be accepted that test code creates instances of this and that like crazy! In a system I am currently maintaining with about 1MLOC where ~40% is test code, I often come across test fixtures with something like 20 individual tests, and each and every one of them creates instances of maybe 5 different entities, builds an object graph, runs some code to be tested, and does some assertions on the result.

This is a super example on how to write brittle and rigid tests, because what happens if the signature of one of the ctors changes? Or the semantics of the object graph? Or [insert way too many ways for the test to break for the wrong reasons here…].

When I come across these tests, I usually factor out the creation of all but the most simple objects behind methods with meaningful names. This has two advantages: 1) It’s more DRY because they can be re-used, and 2) It serves as brilliant documentation. Consider this rather simple assertion that requires a few objects to be in place:

compared to this:

MUCH more clear! The factory method acts as brilliant documentation on which aspects of the test are relevant to the outcome – it is clear, that a mortgage deed which has not yet begun its amortization must report its first term date as the actual principal date.

Go on to test another property of the mortgage deed before amortization:

– and we have already saved us from writing 50 lines of brittle rigid test code. Keep factoring out common stuff, so that the ctor of the mortage deed is still only called in one place… e.g. create methods like this:

which allows me to write cute easy-to-understand tests like this:

This is also a good example on how to avoid writing // bla bla comments all over the place – it’s just not necessary when the methods have sufficiently well-describing names.

Respect your test code

Sometimes I think it is funny to reminisce a bit about where I was and where I am now. One area where I think I have moved quite a lot, is in regards to testing! And I can’t help to think that part of this “journey” was necessary to learn what I think I have learned, but somehow I still can’t put off the thought that I might have gotten here quicker if someone had told me some basic stuff… therefore, I will try to capture in this post a few points, that I pay attention to when writing tests – in hopes that someone might benefit from a little guidance, and hoping not to be categorized as an old man rambling on about his own percieved experience.

To make it more digestible, I will list some points and show examples on why each point is good where I see fit.

  1. Hide object instantiation behind methods with meaningful names
  2. Create base classes for your test fixtures
  3. Make your tests orthogonal

Another way to avoid duplicate data fetching with ASP.NET MVC

If you read my previous post and you thought to yourself: “but that’s a violation of DRY!”, then please stop whining right away!

If you – like me – like to make your dependencies explicit, you will probably think that it is perfectly fine to have to do the following things every time you want to have a piece of data automatically supplied for you:

  1. Apply the attribute to the action method (can be omitted if it has already been applied at the controller level)
  2. Change the signature of the action method
  3. Make sure the data makes its way into the view model handed to your view

In my opinion this is a fair compromise between avoiding writing code and still being explicit about what is going on.

If you, however, feel that there are too many steps above, and you want stuff to happen more automagically, you can do it in another way, that I find almost as attractive… first, create an interface to apply to all view models, that are capable of holding this piece of data – e.g. like this:

Then, make your page level view model implement this interface – from my previous example:

And then modify the action filter to fetch the data in OnActionExecuting and insert the view model for you in OnActionExecuted – like so:

This way, at most two things need to be done to automatically provide a piece of view data:

  1. Make the page level view model implement an appropriate interface (can be omitted if it already implements it)
  2. Apply the attribute to the action method (can be omitted if it has already been applied at the controller level)

It is definitely more DRY, but its lack of verbosity makes it harder to understand. And here, I don’t mean “understand” as in “haha, Mogens is too stupid to understand what is going on” – my point is that I will be wasting a few more brain cycles the next time I look at this action method while trying to figure out how it worked.

How to avoid duplicate data fecthing with ASP.NET MVC

One of the things I like about ASP.NET MVC is that there are so many ways to do everything. I.e. the framework is pretty un-opinionate. This, of course, can also be a serious drawback, because there will more bad snippets on the ‘net where people do ugly stuff in non-preferred ways. And sometimes it is hard to figure out if the way you’re doing something is actually the best for you.

In this post I would like to show a simple trick on how to avoid duplicate data fetching with ASP.NET MVC. That is, how can you avoid typing the same data fecthing logic in every controller action when a piece of data must be available to more than one action method.

In ASP.NET MVC it is actually very easy: use an action filter attribute, and have the filter load the data in the OnActionExecuting method. For example something like this (assuming that you have an ISessionContext that provides information about the currently logged-in user):

This way, if you apply this attribute at either the controller or the controller action level, a new action parameter will automatically be available for you to use. A simple example could be something like this:

By providing the data through the ActionParameters dictionary of the filter context, you can be explicit about which pieces of data will be available inside every controller action.