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.

Working with Windsor and ASP.NET MVC

In the previous post I showed how easy it is to install an IoC container at the system boundary of your ASP.NET MVC application and have it resolve everything from there.

But what I did not show, was where the container came from – in the example, the container just pops out of nowhere on this line:

So how can we implement GetContainerInstanceFromSomewhere()?

Well, I like to do it like this:

Isn’t that easy? And then I have a folder structure in my ASP.NET MVC project that looks like this:

config-folder

It can be seen that I have a folder for each configuration of the system (development, test, prod) and one containing configuration files that are common for all configurations. For each configuration I have a hibernate.cfg.xml to configure NHibernate and a windsor.config which is loaded by the Windsor container in each particular configuration.

My development/windsor.config looks like this:

It can be seen that my development configuration is used to Cassini running on port 1766 🙂 moreover, it can be seen that my development configuration is using a fake, logging email sender, which – much as you would expect – only logs the content from emails that would otherwise have been sent.

Of course, the configuration files will not automatically be available to the web application the way they are organized now – therefore, my web project has a post-build task with the following two lines:

– thus copying the common configuration files along with the development configuration files to the base directory of the web application.

This also means that my build script must overwrite the development configuration files when building the system in a deployment configuration. It can be achieved as simple as this (using MSBuild):

Here I have define tasks for compiling the web site (“build”), deploying the binaries + views + content files (“deploy”), deploying common configuration files (“deploy_common_configuration_files”), and then one task for each deployable configuration: “deploy_test” and “deploy_prod”. This makes deploying the web site on my test web server as easy as running the following command:

What is left now, is to make sure that the different sets of configuration files are valid in the sense that Windsor can resolve everything right. That is easily accomplished in the following NUnit test:

This way, if I introduce a service in my development configuration that should have been implemented by a production version of the service in my production configuration, I will immediately know about it.

I think this post covers an easy and pragmatic way to control multiple configurations with Windsor and ASP.NET MVC. Of course you might want to split out the configuration-specific parts into multiple files instead of having only a windsor.config for each configuration. What I mean is something like this:

The great thing is that we can refactor our configuration with confidence because of our test. And if we want to be extra-certain that everything works as expect, we might begin to add assertions like this:

ASP.NET MVC – dependency injection by IoC container

One thing, that I have seen done wrong in so many ways, is DI in relation to ASP.NET MVC. Just to get things straight for everyone – including those, who have been living under a rock for the last 30 years – here’s a glossary:

  • Dependency injection (DI) – is exactly what it says, i.e. dependencies are injected. So your business methods don’t just instantiate order processors, they have them injected for them to use.
  • Inversion of control (IoC) – is when program flow is no longer just sequential. In many cases just a fancy term for a callback. In this case, it signifies that your classes may call stuff on instances on other classes, that are handed to them – which happens by DI.
  • IoC container – is a thing, that facilitates the above and removes the pain.

Quick, off the top of my head implementation of an ASP.NET MVC action method

Now what happens when we want to test this? Well, we definitely need the database to be there, otherwise we will probably get some nasty SqlException stuff happening. There may be other stuff going on, we don’t know. Or even if we know now, we will not have a clue in a few months! – because what if some class, on which our ProductService depends, changes? Or changes its dependencies? The product service is tightly coupled to everything that is architecturally beneath it. We need inversion of control!

Naïve IoC/DI example

Now, we have DI-enabled our service layer. It can be seen that the repository gets its NHibernate ISession from a session provider, that can probably be configured with a connection string somewhere. And we have a complex business rule inside a specification, and a service to use the repository and the specification together. This is much better, because all dependencies are explicit and injected from the outside. But this code is still not perfect – there’s way too much going on, the classes are all concrete, and there is no way to test the action method without instantiating all this stuff. And what happens when the product service is used in 100’s of places in the system, and suddenly it needs another specification in its constructor to decide whether the current user can be given a rebate? Damn! Back to work… let’s try again:

Service locator IoC/DI example

Now it’s much clearer again. But what is MyContainer? Well, it’s actually pretty simple: it’s a generic factory! And this time we are using the factory to supply a dependency when we need it and let the factory decide where to get it. Then it may deliver a new instance, an instance from a pool, an instance tied to the current HttpRequest or a singleton or whatever it feels like. This is the service locator pattern, and it’s better than the second example, but still – your code will be cluttered with calls to your container, so unit testing will not be as easy because your need to have a container in place or mock it.

This brings me to how to do it with ASP.NET MVC – the important thing is that we have one single call to container.Resolve<...>. We do it by taking control over how controllers are created, because the controller creation is the single entry point into as ASP.NET MVC application. Here goes:

ASP.NET MVC with IoC/DI

global.asax

MyControllerFactory.cs

And now – the best thing about DI: The class is pure! Look!

ProductsOnSaleController.cs

It is plain and simple, depending on a product service only, which gets automatically injected by the container. Easy to test, easy to extend. And we are probably going to write 100’s and 1000’s of action methods, so we are going to save a lot of work and grief on that account – thanks to DI and IoC.

I think this is THE way to do dependency injection in ASP.NET MVC controllers. I will show in another post how you can configure Castle Windsor with ASP.NET MVC to support multiple configurations (e.g. IEmailService is FakeLoggingEmailService on the developers’ machines and RealLiveSmtpEmailService in a production environment.

Helping future me

Usually, when writing code, you adhere to some conventions on how your stuff should work. At least I hope you do – otherwise your code is probably a mess!

Sometimes, these conventions can be enforced by using some patterns to allow for compile-time checking – one example, that I can think of right now, is using the visitor pattern to implement multiple dispatch, which is explored a little bit in another post.

But what about conventions, that can only be checked at runtime? Well, how do we usually check stuff that can only be checked at runtime? – by writing tests, of course!

One project I am currently involved in, is written in ASP.NET MVC. All form posts are done using the automatic binding features of the framework, and I am following the convention that the names of my view models should end in “Form” – so as to enabling me to easily distinguish my form posting DTOs from my other view models. What is more natural, then, than performing the following test:

That is, I am running through all controller types, getting all actions, and checking the the parameter types are either in the array of accepted types ( IsPrimitiveType) or a “true poco” (which in this application is a simple view model whose name ends with “Form” and comes from the right assembly).

This way, I will always know which types are used to deserialize forms. Great! But what about that pesky MissingMethodException whenever I forget to provide a public default contructor in my form models? Easy as cake! That part is checked by the following test:

These two tests combined, will assert that nothing will go wrong when submitting forms in my ASP.NET MVC project. That’s just nifty! And I really like the notion that I am helping future me.

Customizing the NHibernate mapping when using the AutoPersistenceModel of Fluent NHibernate

EDIT: Please note that this way of configuring Fluent NHibernate is obsolete since the RCs. Look here for an example on how to customize the automapping on Fluent NHibernate 1.0 RTM.

Fluent NHibernate is cool because there is too much XML in the world – so I appreciate any initiative to bring down the amount of XML. Configuring NHibernate using simple code and strongly types lambdas is actually pretty cool.

However, there is also too much code in the world – therefore, the AutoPersistenceModel is my preferred way of configuring Fluent NHibernate. It allows me to focus on what really matters: my domain model.

But don’t you lose control when all your database mapping is done automatically adhering only to a few conventions? No! You can always customize your mappings and complement/override the auto mappings. But then we can easily end up customizing too much, and then we are back to writing too much code.

Therefore, I would like to show how I use attributes to spice up my NHibernate mapping and add that tiny bit of extra customization that I need. I would like to be able to make the following entity:

That is, I want to be able to describe some extra mapping related stuff by applying a few non-instrusive attributes in my domain model.

How can that be accomplished with Fluent NHibernate? Easy! Like so:

and then I have made the following attributes:

IndexedAttribute.cs:

UniqueAttribute.cs (works with ordinary as well as composite unique constraints):

LengthAttribute.cs:

EncryptedAttribute.cs:

If you are an extremist PI kinda guy you might think this is wrong – and I might agree with you a little, but I am also a pragmatic kinda guy, and I think this is a great compromise between being fairly non-intrusive but still expressive, effective and clear.

Why I use Guids for primary keys all the time

Fabio Maulo explains and shows the difference between using Guid, Hilo and native primary keys with NHibernate and the batcher: NH2.1.0: generators behavior explained

Reallly insightful post (as always), and this one is mandatory reading if you

  1. are using NHibernate
  2. are not using NHibernate because you think you think it performs badly compared to your own hand-rolled ADO.NET data layer

I claim (without any empirical knowledge besides my own experience) that almost all db access in reality performs much better with NHibernate because of batching and futures. You CAN outperform NHibernate in synthetic benchmarks and stress tests, but for real-world usage, optimizing and doing your hand-rolled ADO.NET thing is far too cumbersome. Not using an ORM is like insisting on using assembly language instead of C# “because it’s faster”…

How to (really) implement your own ActionFilterAttribute

In ASP.NET MVC you may “tag” your actions with attributes derived from ActionFilterAttribute and automatically have their OnActionExecuting and OnActionExecuted methods called before and after the framework invokes your action, thus achieving a simple form of method interception by using attributes.

Pretty simple model, but it falls apart if you are using an IoC container to wire things up. Moreover, having application logic embedded in properties is sort of icky. It just so happens that we can solve both problems and end up with a pretty nice solution at the same time 🙂

First, create the interface you wish to use to denote an action filter – e.g. something like this:

Note that I have used interfaces for the arguments. This allows us to decouple the action filter from the framework classes, thus making our stuff more easily testable.
In this example I have only put one method – ProvideViewData – on IAfterActionContext, allowing my action filters to insert additional key-value-pairs into the ViewData. More methods should of course be added if they are needed.

Then, create the actual action filter attribute, and make it accept a type as ctor argument – e.g. like this (assuming I want to resolve dependencies through the Windsor container installed as my controller factory):

And then implement the before and after argument classes – e.g. like this:

Now you may use the action filter like this:

where your IProvideProductCount will have all its dependencies automatically resolve by the container. That’s just sweet 🙂

In this example I made this simple implementation:

– thus allowing any views rendered from an action tagged with [ServiceFilter(typeof(IProvideProductCount))] to show how many products we have.

If your action filter attributes need arguments, then it’s another story. I wonder how one could get around to implement that?