Spinning Up A Static Site Using Node

It always frustrates me that there is no ‘right click –> start website’ feature in windows or on mac. But I found something just as good. It is a node module which you can install globally with this command….

Then when you are in the folder you want to spin up as the / of your site you simply bash this in….

Then you get a nice website at that location.

TDD Simplified in 5 Steps (Video & Book)

This blog post will introduce my E-Book and Talk (in video format at the end) titled ‘Test Driven Development Simplified in 5 Steps‘. Scroll to the bottom now to get right to them or read on for a quick introduction.

Test Driven Development (TDD) has so much information available on it that it is easy to become overloaded. This overloading of information often leads the newcomer down the wrong path. And even more experienced TDDists can still sometimes make decisions which devalue the practise. Whilst best efforts are made to use it on projects, months/years down the line it’s value can diminish. On a number of occasions I have seen tests abandoned and commented out just so that development work can continue.

Over the time that I have been studying and practicing TDD I have had the chance to notice some recurring problems, I have also had the chance to see what works well. So a few years ago I started my own project on the side to see if I could tease out a way of working which was less confusing. It meant I had to read up on the good and the bad behind TDD to try and identify pitfalls. I got some useful insight from doing this and since then most of the TDD projects I have been involved with have worked well. sss

I distilled what I know down to a number of steps which are all complimentary. The steps also have strong roots in good engineering practices in general.

The 5 basic steps to simplifying Test Driven Development are….

  1. Observing Objectives – making sure you set your objectives at the start of the project will ensure you don’t waste time on what doesn’t work
  2. Layering – creating a tiered structure will help you to scale your code and write tests that can pinpoint what they need to much easier
  3. Decoupling Tests From Implementation Details – decoupling should be the goal of refactoring if it’s true with code it’s also true with tests
  4. Extracting the benefits of BDD and Integration Testing – get the ubiquitous language of BDD and the depth and coverage of Integration Testing
  5. Domain and Framework Separation – probably one of the biggest problems in code bases, the framework you use is just another application; treat it so

It is by no means the final word on TDD. But these are five areas that I have come to consider important starting points to be able to really get value whilst minimising overhead.

E-Book : Test Driven Development Simplified

I decided at the start of this year to write down some core ideas which are based of my own experiences and research. The core ideas are split into 5 areas and I call these ‘steps. They are designed to be complimentary to each other. The steps are written in a small E-Book which you can download here.

The Video : Test Driven Development Simplified

The book accompanies a talk I do in London and in Reading. The talk lasts for 1 hour and goes over the steps. I recorded this talk onto video and you can find it below….

Screencast : TDD Simplified in 5 Steps (Angular)

I recorded my talk called ‘Test Driven Development Simplified in 5 Steps’ onto video. It is about an hour long. It goes over the 5 steps that I lay out in my E-Book. It uses Javascript/Angular for the examples.

The 5 basic steps to simplifying Test Driven Development are….

  1. Observing Objectives – making sure you set your objectives at the start of the project will ensure you don’t waste time on what doesn’t work
  2. Layering – creating a tiered structure will help you to scale your code and write tests that can pinpoint what they need to much easier
  3. Decoupling Tests From Implementation Details – decoupling should be the goal of refactoring if it’s true with code it’s also true with tests
  4. Extracting the Benefits of BDD and Integration Testing – get the ubiquitous language of BDD and the depth and coverage of Integration Testing
  5. Domain and Framework Separation – probably one of the biggest problems in code bases, the framework you use is just another application; treat it so

This is the Screencast…

Angular Directives are Just HTML

In this article we will take a look Angular Directives, how they are dealt with during the Angular bootstrapping pipeline and how they should be designed if you want to architect large-scale Javascript Angular applications.

It follows on from the article I wrote the other week whose purpose was to give us a different perspective with which to think about the types of objects Angular gives us to work with, these articles will focus around making us better Object Oriented Software Architects who can leverage frameworks to fulfil our objectives without letting them take over!


The Separation of Concerns (SoC) is a design principle in Software Engineering which deals with separating the design of code into distinct parts that deal with their own concerns.

I have noticed that since Single Page Applications (SPA’s) have become more prevalent it’s absence has become more pronounced and I think there is a reason; if you look at the evolution of Javascript being regarded originally as a small scripting language for doing trivial tasks it is easy to see over time how the desire to separate concerns in Javascript may not have been as great as in multi-developer large scale C# or Java applications. However, with modern day (SPA’s) being as large or if not larger than their backend counterparts it would be wise to hold onto tried and tested design principles for the sake of well maintained and extensible code!

How Angular Directives Work in Angular

Angular Directives are a constituent part of an Angular code base that often violate the Separation of Concerns principle. This artcile will attempt to tackle it’s subject in two phases. Firstly an explanation of how they work. And secondly what this means in terms of their limitation. In order to be better Software Architects it’s important to understand the limitation of any tool you use in so that you can break out of using the tool when appropriate to do so.

Step 1

The first thing we do is declare some html on a page. The html is actually HTML 5 ‘syntactic style’ meaning we can insert anything we want into the tags. What this allows us to do is insert a unique string (in this case called ‘my-directive’) which will let Angular bind some behaviour to.

Step 2

Okay that was easy, now let’s make a bit of Angular code written in Javascript. This code is the Angular Directive declaration itself. It’s nothing special but it conforms to a special contract which Angular understands. We let Angular know it’s a directive by attaching it to a module and calling it a ‘directive’ (line 1).

Deconstructing an Angular Directives Code

As you can see from the above we have declared a very simple directive. The syntax for Angular Directives can be difficult to memorise. They have a billion different confusing options (some of which override each other), have complex set up and tear down, and the string interpolation stuff going on at the scope.ngModel level is enough to give anyone a headache. But really when you get down to it they have 3 main things going on you need to be aware of.

  1. Compile(line 9) is a function that you write that will be called by Angular during it’s compile phase. What this means in plain speak is that Angular is going to interrogate the html (which you just created in the template property on line 8) and is going to turn it into something that Angular can deal with later down the line (called a template function).
  2. Link(line 13) is a function which is responsible for manipulating the DOM. It will have the scope injected into it. The scope is just a little object which helps our Javascript talk to the Angular View (Template). I like to think of it as glue between Javascript and the View. The link function can only be invoked ‘after’ the compile function because as well as the scope it also needs access to DOM elements such as the attributes and elements. It can only deal with compiled html (step 1) and thus will be called when this phase is complete.
  3. Controller(line 20) is no different to any other controller inside angular. Simply put all we are doing is declaring it in the same file as the directive. With this in mind we get access to one of the main features of Angular and more specifically Angular Directives; Dependency Injection (DI). This means that we can inject in a dependency of our own choosing at this point. And because we also have access to the scope we can ‘attach’ whatever logic resides in our application to the DOM using this function. It’s worth noting that we also get DI in the constructor function of the directive but the controller is independantly testable.

The Compile, Link and Controller functions will be called by the Angular bootstrapping code in this order…

1 -> Compile
2 -> Controller
3 -> Link

Here is a diagram which shows how the compile and link function serve to generate HTML which the controller will control!

Angular Directives and Controllers Pipeline
Angular Directives and Controllers Pipeline

NOTE : The link function is invoked (after) the controller because it is the one place that needs to be able to access the controllers of other directives.

What does this mean?

Looking at the above steps we can see that the directive just does two things…

  1. HTML Modification (Compiling and Linking)
  2. HTML interaction (Controlling)

From a technical perspective the directive is nothing more than a placeholder in the view, it allows to us to respond to events that happen in the browser and it allows us to dynamically update the view and call our own code.

So What’s New?

Well … the native HTML DOM Api built into any modern browser does already allows us to do this in the form of HTML and it too can be accessed using Javascript. So… looking at it this way an Angular Directive is simply allowing us to extend HTML… enter the Meta Framework….

The Meta Framework

The word meta means to ‘refer to oneself or genres of itself’. This is a great description of what a directive does. The directive is a self referential description of the thing it creates (HTML). Because by using HTML and some javascript we have just extended the HTML description, we have created ‘edge’ so that you can connect your own logic to it in a way that is maintainable and comprehensible. This is the essence of the Meta-Framework aspect of AngularJS!

This fundamental truth leaves us with conclusion that a directive is simply an extension of HTML and defines the core theme of this article….

Angular Directives are Just HTML.

Separating Concerns – The In Page Sql Dilemma

If you have been programming web applications long enough or you use certain frameworks you may be aware that some web frameworks will allow you to write SQL code in the view. For example PHP allows this and so does .Net. As I’m sure you are already saying to yourself it would be a terrible idea to exercise this feature. Quite simply, hard coding data access into a view quickly becomes a maintenance nightmare. There are two reasons for this…

1) a single change to the structure of the data and your view breaks
2) it’s very difficult to understand context when you lump data structures in with the view behaviour and structures

So, What implications does our new found insight about directives and the little consideration we just had about embedding persistence into the view give us?

Well…consider the following code :

The above has a design flaw… one line in particular is the problem. Can you spot it? It’s (line 32 – line 40) where most importantly CustomerService.getAllCustomersWithBookings() is accessing an API in order to get data and map it to a property on the $scope.

Now… it just so happens that the API is a remote HTTP JSON based but, for the purpose of this discussion this fact is irrelevant.

What is relevant is that we didn’t create the return object customers. It is returned from an application that we do not hold the right to change and have no control. Even if we did it wouldn’t be wise to force ourselves to have to.

What we now have is a situation which is EXACTLY the same as the SQL dilemma we had at the start of this section. Because we don’t own the interface to the returned object customers it is no different to accessing a data persistence object directly in the view. Another way to think of it would be like writing Javascript which performs business logic inside script tags, any javascript professional would probably avoid doing this without good reason as it isn’t maintainable; it just isn’t a good idea to write business logic inline in a view!

Designing software like this where the business logic is so close to the view poses problems that shouldn’t be underestimated let’s just recap….

First Problem : risk

The risk we carry is that if the customers object ever changes it’s schema… our view breaks. This character of software design is known as brittlety. One change in one place will have unexpected consequences in another part of our application (the view).

Second Problem : cognitive dragging

Because the design is not orthogonal, over time; from a cognitive perspective it will be difficult to reason with and it will be hard to see exactly what responsibilities the directive holds, this will have a slowing effect on being able to comprehend and thus maintain the code base.

This type of design in Angular directives is extremely weak. At the start of a project when the code base is small it’s possible to manage the risk associated with this design flaw. But as the projects grow inevitably features will start to break. The only option is heavy refactoring or in the worse case entire rewrites, this puts whoever is paying for the software at extreme risk.

Breath….Breaking Out Layers

I’m not one to throw the baby out with the bathwater. So if you do have directives already like this stay reading, I am going to show you how you can address the problem with a clear focus. The approach is the same across any Object Oriented software and is called layering. For a more detailed explanation of it then checkout my E-Book about TDD. In almost all the projects I have worked on in a commercial capacity we have always ended up needing a minimum of 3 layers, Persistence Modelling, Business/Entity Modelling and View Modelling. The following diagram is from my E-Book.

Angular Architecture Viewmodels
Angular Architecture Viewmodels

The basic premise is that you decouple the directive from deeper parts of your application using something Inversion of Control (IoC).

For example the CustomerService (which by the way is a terrible name, please see my other article) we saw should be separated from the directive by virtue of an an abstract interface, I mean this in the looser sense of the word being an implicit affair as opposed to a strongly typed interface, however the core idea is the same. What I mean is that the directive should talk to an interface not a concrete dependency. Read on…

Enter the ViewModel

What we need to do is create an interface on the Javascript object responsible for returning our data. And that interface will be responsible for exposing the data structure that the view is going to render not the underlying object.

This data structure has a special name. Because it is a model that is intended for the view we call it ‘The ViewModel’ I am sure you have heard of ViewModels before. Lot’s of people can get hung up at this point in the MVC/MVVM debate, however the focus we are discussing here is not the design pattern it is the motive. We are looking to decouple our application using a data structure designed for the view : The ViewModel. Here is the refactored code….

There are 3 main steps that I have done in this refactoring.

  1. Introduced a single endpoint (Line 1-12) which is responsible for communicating with and returning a data transfer object customersDto (Line 22)
  2. Introduced a ViewModel layer (Line 14-34) which will map the customersDto to a ViewModel property(Line 25)
  3. Completely decoupled the Directive from the internal construction of the viewmodel by simply assigning it once it is in the controller(Line 52)

We now have what is called a Layered Architecture. This type of Architecture has many forms but essentially the premise is to shield each layer from the other. By doing this we reduce coupling. And by reducing coupling we will find that our software becomes less brittle. Over time we begin to refine our layers. Some layers will become more abstract. It is our job as Software Architects to consistently refine what each of these layers represents. You will find over time that you will discuss, change, change back, disagree, agree and go round in circles about these layers and their purpose. This is fundamentally what designing software is all about. Some people call this process incremental design. I call it programming.


  • At this point you might be wondering why we didn’t resolve the promise in the controller. Well it’s best to use something like UI-Router in this case to force resolution before the controller to keep the controller clean.
  • I have used 2 layers not 3 (my recommended minimum). I have done this for brevity.


As our application grows the sort of poor design we saw at the start of this article will with direct view to data transfer or persistence object coupling will be difficult to maintain. In the beginning it will feel natural, it will feel like just enough to get the job done. Be wary because over time it will slowly grow, slowly morph and change into a big slobbering mess growling at people who come across it and screams ‘feed me developers aaaarggggg’ !!!!

slobering angular directive
slobering angular directive

You will notice you fix a bug in one area only for it to be repeated in another. You will realise things breaking in odd ways. You will pull your hair out on a friday because you want to go home but you are stuck in work using chrome debugger :-(. But, most of all you will put the code base at risk and slow development…

In our refactored version we did something that at it’s core is quite simple. We decoupled implementation of modules that do different things. We separated concerns. We layered our application to hide the internal design of one concern from the internal design of another and we did this using the ViewModel!

By realising that the Angular Directive is really just a way to describe HTML we see how to leverage this to connect our application in a minimalistic way to some Javascript code that does ‘other stuff’. We see that the frameworks real purpose is to render the view not to handle other things like persistence. We realise we have to keep Angular working on what is good at. Not what it is trying to be good at. It is up to us to make sure we don’t give it too much to do. It is our responsibility as Software Architects to make wise decisions about when and when not to leverage a framework.

Now can begin to realise a more stable way to construct large scale applications which are decoupled and easier to maintain. Good luck!

Angular Services Are Just Javascript Objects

In this article we will look at Angular services, how they are created inside the Angular source code, and then we will draw a conclusion which will hopefully make us better Software Architects. The central concept of this article is also applicable to Angular Factories (which are almost identical in their use but have a couple of subtle differences). See the note I have made further on in the article for clarification on this.

On his blog Douglas Crockford states…

“JavaScript is a very nice dynamic object-oriented general-purpose programming language”

This comment is important because we often get caught up in the dynamic and functional aspect of the Javascript language before remembering the simple truth that ‘Javascript is just objects’! Forgetting this can cloud our judgement and make us focus efforts inefficiently treating it in a way that is counter intuitive, it can inhibit our ability to use age old tried and tested Object Orientated design principles to architect large applications.

Angular Services, in my opinion, suffer from the problem. They are often treated as a one stop shop to denote every architectural naming and object creation decision where the concept of the service becomes the fundamental unit of currency inherent in the overall design of the system.

To start this discussion I would like to just explain how an AngularJS service is created. The majority of the following code will peer into the Angular source code, so hold onto your hats – we are going down the rabbits hole!

Step 1 – Our Declaration

We make a declaration to AngularJS to create a ‘Service’ within our module called ‘Dashboard’. Nothing special but here you go…

Step 2 – Angular Services Bootstrapping

Then we start our application and Angular begins it’s bootstrapping process. The very first function that gets called is ‘invokeLaterAndSetModuleName()’ (we are now in Angular land btw).

What this code does is return a function which takes a scoped parameter called ‘factoryFunction’. This variable is actually our service declaration function (the Dashboard) detailed in step 1. It adds our service function onto the invokeQueue[].

Step 3 – The Set Up

The next relevant step is how the service function that we placed in the invokeQueue[] is now invoked. It is done in another Angular function called loadModules. This function (and I have deleted the irrelevant code from it) searches all of our modules and instantiates the services we declared and that were placed into the invokeQueue[] by Angular.

The most important line you need to be aware of in the code is line 11. This line is using a Javascript apply (aka the ‘function invoker’ method). It’s a highly generic function (rightly so) which dynamically invokes all Angular base types (Constants, Factories etc etc). Picking apart this line we see some interesting interfaces in the debugger…

In other words what the code is really trying to say is this…

Step 4 – Preparing for Invocation

Once Angular has used it’s nifty generic module and object loading to bootstrap and set up our application it must now actually start to put pen to paper and spin up the objects. AngularJS uses this object called the $provider and here is the code…

Focussing on line 15 we can see a call to $injector.instantiate(constructor); it’s important to note that at this point the ‘constructor’ argument is just the anonymous function we defined in step 1 (our Dashboard).

Step 5 – Finally

The very final call is the instantiation method, watch carefully!

Did you see it? Line 9 if you didn’t. AngularJS just used Object.create to spin up our Dashboard, so there we have it… Angular services are just Objects! No magic. No secrets. At the fundamental level they are just Javascript objects.

NOTE : Whilst this article is about Angular Services the same applies to Factories. The fundamental difference between Factories and Services is that Services return the object through a function constructor. This means that you can use the keyword ‘this’ inside the Service but not the Factory. Both Services and Factories are also implemented using the Singleton Pattern. If you are not storing state then it is good to use a function constructor inside your Factory or Service definition and return this to main thread of execution as your object. That way the consumer will be forced to use the ‘new’ keyword and this will avoid the obvious state implications with using Singletons.

What does this mean?

Well…If an Angular service is just an object why do we care if they are services? Well the truth is we don’t really.

You see the fact that something is called ‘a Service’ from the perspective of AngularJS is merely fluff. It is window dressing. The reason we dress our objects up as ‘Services’ is because we are using a framework that tells us to, someone has decided that the thing that does the job of this ’Service’ will be called a ‘Service’… that is all. We call it a service so that Angular can ‘handle’ it. Really what this boils down to is Angulars ability to offer us…

  • Dependency Injection
  • Garbage Management

These are great features in their own right but… it doesn’t take us away from the central principle of this blog…

AngularJS Services are just Javascript Objects.

Pure Object Orientation – Design as a Metaphor

The purpose of an Object Oriented language is to allow us to write the description of a programming problem that makes sense to us. Since humans think in terms of objects it is much easier for us to reason with and craft software if we have a description in front of us that models how we perceive the world or the problem. Writing object definitions in this sense are just metaphorical descriptions.

For example take the following design/architecture diagram (I often see this sort of design diagram in projects).

Angular Services Architecture as services
AngularJS Architecture as servcies

The above design is problematic; we have let AngularJS take over. Because we have used Services we have decided to call everything a xxxService. What’s important to consider here is; does the word ‘service’ inserted on the end of these object names really offer us any value? If we are designing a code base of metaphorical descriptions are we really offering anything of value by repeating in the name what the framework needs to know and the consumer of this object doesn’t?

I don’t believe we are. Or to put it more specifically I believe we have expended an ‘opportunity cost’. We spent an opportunity, the opportunity to give us a clear definition of intent by using the name to tell us what it is, not what it is made from!

I would personally design the above like this…

Angular Services Architecture as objects
AngularJS Architecture as objects

Now we have a very clear definition of what each of these objects does from an OO perspective. We have not laboured ourself with how they are created. Because… quite frankly we do not care, we just care that they are objects and we care about what they do not how they came to be!

A Better Way To Name Angular Services

My recommendation is to avoid calling everything in an Angular application a ‘service’ just because you have used the service type to declare it. Of course if something truly is a software service then call it so, but in the majority of cases of services I have seen are not. There are usually other objects bursting to escape from badly named xxxService type objects. There are usually many types of objects which could have a real world descriptive meaning which have all been loaded into one god like service!

Think hard about what the service is doing and name it according to it’s function not it’s form. You are after all a designer of Object Oriented software.

Well… hopefully this blog has shone a light on an area of Angular Design and Architecture that will help you in your travels into creating software that is easy to read, easy to modify and fun to work with. Hopefully it will give you some pause for thought about how you name the constituent parts of your Object Oriented AngularJS applications.

If you are interested in knowing more about AngularJS architecture my TDD E-Book has a section called ‘Layering’ which is helpful to use to create non-trivial Angular applications.

AngularJS Dependency Injection has 3 Key Benefits

This blog will talk about some hidden benefits of AngularJS Dependency Injection. It is really about Inversion of Control (IoC) in general and it’s use in creating non-trivial applications.

As a signed-up advocate of the Software Craftsmanship Manifesto I’m always interested in keeping design of software decoupled and I talk about this in my free e-book about TDD. This leads to less rigidity in design (which over time will make development slow and difficult). Take, for example, the following code…

We can see from the above code we have created a class like structure (using a function constructor) which defines an ‘Order’. Then we have used this in 2 separate controllers to make 2 different types of Order. One for apples the other for oranges.

Identifying Software Coupling

At this point we have a design flaw… We have too much coupling between the controller and the Order meaning they are highly connected. A change to one will likely mean a change to the other.

Why is this important? Well.. what if we want to change the design of the Order class? If we do, then we have to change all the references to it as well in the OrderControllers; we have exposed the internal design of ‘Order’ to all the consumers.

Added to this what if we decide not to use an alert box for showing the order? We now have to change all of that code in the controllers too and use some other alert mechanism. What is worse, is if at runtime we don’t have access to the alert box we could inadvertently crash/hang the application, for example if we are running this in a headless browser (such as PhantomJS). Of course this is a contrived example but hopefully you can see the problems inherent in direct consumer to object coupling.

What we want to do is hide the design of our Order from the consumer. Then, when we need to change the order we will not have to introduce risky and/or difficult changes to the consuming code in the controllers.

Dependency Injection to the Rescue

The answer is to ‘invert dependencies’ this is known as Inversion Of Control and is a fundamental tenant of good OO design. Now, let us introduce a 3rd object which will be the holder of this inversion. It is called the OrderMaker….

We have used a revealing module here in order to make sure that we totally encapsulate an order once and throw it away by exposing a single public function with it’s own scope. As you can see now the OrderMaker will expose the minimum amount needed to the calling code (the string id of the order) and will do the heavy lifting of the Order itself.

Then we leverage the brilliant dependency injection feature of Angular to simply ‘inject’ a fully loaded OrderMaker into our two controllers (in reality the actual implementation would be different but I am showing what goes on in the internals of angular to give a clear picture of the power of IOC/Dependency injection)….

There are three clear benefits to doing this…

  1. The design of the order can be refactored much more easily since we only need to change it in one place (the OrderMaker)
  2. The controllers are much easier to understand since we only have to read one line instead of 6 to know we are making an order
  3. We can easily overwrite the OrderMaker with another implementation which leads us to more flexible design

Quite often we hear about these shiny framework features without knowing why they exist in the first place and Inversion of Control is nothing new. It is deeply intertwined with Object Oriented programming and was identified as a ‘thing’ long before Angular or even Javascript for that matter was around.

A Picture Reference to Inversion of Control

In order to visualise Inversion of Control (which Dependency Injection helps us achieve) I sometimes find it handy to refer to the following two diagrams.

The first shows a typical scenario with no Inversion of Control

With no Dependency Injection or Inversion of Control
With no Dependency Injection or Inversion of Control

We can see how some consuming code calls a supplier directly and has implicit knowledge of it’s internal design. If we wanted to reduce this coupling we use Inversion of Control by leveraging Dependency Injection. In essence we wrap the supplier code in an interface and inject that interface into our Angular controllers. The following diagram is the result of having inverted dependencies.

Using Inversion of Control by leveraging Dependency Injection
Using Inversion of Control by leveraging Dependency Injection

As the diagram shows an interface is introduced. Notice how the dependency of the supplying code is now pointed at the interface. We say that the code ‘implements’ that interface. And the consumer code will call that interface not the original code. This is the art of loose coupling.

Many design concepts exist which are a function of pure OO and being aware of them is vital if you want to excel as a designer of non trivial computer applications and become a better Software Architect. Hopefully this blog post has shown you a classic bit of theory by leveraging a modern framework. So… next time you find yourself adding lot’s of code that can see the internals of an object, think about inverting dependencies using Inversion of Control and Dependency Injection…..

5 Javascript Test Doubles You Should Know About

In this blog we will have a look at 5 Test Doubles. In my free TDD E-book I only cover 2 (the Stub and the Spy) since my personal experience is that when taking a state based approach to testing this is all that is needed. But it’s good to know these 5 because most likely they will be dotted around code bases and being able to identify them is important.

What is a Test Double?

A ‘Test Double‘ is a piece of code which can be used in place of code within the context of a test to help us make assertions. Whether you use TDD or BDD or you simply write tests after you write your code the definition of Test Double should not really alter. Of course it does depending on who you speak to but if you look at the history behind them (and by history I mean publication of books*) then you can that there is a rough conclusion about the different types. The most important thing we can do as professionals is to understand all terms, and what they mean so that in conversation, we can identify what we are speaking about more easily.

* Test Driven Development, Kent Beck. Growing Object Oriented Software Guided by Tests, Steve Pryce and Nat Freeman. Xunit Test Patterns, Gerard Meszaros

What is a Test-Double?

A Test Double is simply an object that can be used in place of a real world object when executing production code with a unit-test. They have 3 main purposes…

  1. To stop IO from happening – this would makes tests slow an unreliable since they should be able to run anywhere
  2. To track the internal state – this means we can check certain things happened or were left in a certain state once execution has finished
  3. To force the system into a desired state – sometimes we want to pretend we the system is already in some predetermined state

I will use Javascript and AngularJS to demonstrate the different types.

1) The Dummy Object

The first and very foremost type of Test Double is a Dummy Object. This is simply a test object which overrides a real world object when executing production code in the context of a test. Take, for example; the following code :

In it we have an object called an Alerter, this object will actually be responsible for creating a javascript 'alert()' command when it is injected into the Angular controller.

However we really don’t want the test to try and launch an alert box (it’s generally not a good idea to allow tests to invoke IO operations). So what we do is create a Dummy Object which matches the design of the Alerter.

The dummy is then used in place of the Alerter. The key defining attribute of the dummy object is it’s simplicity. It just serves as a sort of blank holder to allow the code to get past some point without creating undesired behaviour before we hit the portion of code we want to test.

2)The Stub Object

The Stub builds on the Dummy object, it adds functionality that will allow a test to depend on the output of of the Stub. Take the following code:

We can see here that our Angular controller needs to load a result from the HttpAuthenticator. If we try and unit test this controller we hit the same problem we hit in part 1. Our $http object will cause an IO operation which we want to avoid. We aren’t testing http after all we can assume the developers of the $http module will do their job properly for now and will make an api that works. What we want to do is test that our code that runs inside the controller runs as expected when authentication is successful. We want to check the bit inside the ‘if’ statement. So what we do is create a stubbed Authenticator like this…

When we now inject the AuthenticatorSuccessStub instead of the HttpAuthenticator we can force our application to reach the correct pre-condition : that the user is authenticated.

Bottom Line : When you want to force-set what a webserver responds with (in your test); use a Stub.

3) The Spy Object

The Spy also builds on the Dummy object. It’s purpose is to ‘sniff’ out and detect when a method on it was called. This helps us when we want to use ‘state based verification‘. It works like this…

The somewhat truncated code I have shown above should be enough to demonstrate how the spy works. It’s just a variable which is set when the test double is injected into the controller and run. It means we can check that the Authenticator.load() function was actually called.

The Spy can be extended to also capture what was passed to a function. They can track the what and the how. This type of test double is excellent for ensuring that your application ‘dials out’ to an IO boundary with the correct functions and the correct arguments.

Bottom Line : When you want to check what a webserver was sent; use a Spy.

4) The Mock Object

The Mock Object builds on the Spy object. In it we declared our Spy property as private but then expose the meaning of the Spy through an actual function; this shows the test an interpretation of what the calling code is doing. The benefit with a Mock is to show behaviour. Fundamentally this allows us to move from ‘state based assertions’ into a realm known as ‘behaviour verification’. Personally I am not a fan of this double, however it is worth saying that a lot of developers are using Mock Objects with behaviour style testing. The idea behind true mocking is to isolate each individual object in the system. It is a not a practice I personally feel I need to use because state based seems to give me enough confidence but it’s worth knowing about.

NOTE: Mock Objects should not be confused with ‘Mocking Frameworks’. Mocking frameworks should really be called ‘Test Double Frameworks’. They are simply a suite of classes that allow us to dynamically generate Test Doubles. There is a lot of confusion and it doesn’t help that the word ‘Mock’ is used colloquially to refer to Test Doubles. The most important thing is to be aware of this distinction. It helps to clarify this in conversation where not clear.

Bottom Line : A Mock is a specific type of Test Double. It is also a colloquialism for the term ‘Test Double’. To add confusion a mocking frameworks helps us to make all types of Test Doubles.

5) The Fake Object

This is perhaps the most interesting and dangerous beast of all Test Doubles. The Fake Object actually mimics business logic. It can be used where you don’t have access to a real world object whose functionality your system depends on. You can see below that there is an ‘if’ statement. Generally speaking if you have an ‘if’ statement in a Test Double alarm bells should be ringing because anything with conditional logic can break. And if it can break… well it probably needs to be tested in itself.


In this blog we learned…

Dummy Objects – Are simply objects that allow our code to run/compile.
Stub Objects – Are types of Dummy object preconfigured values which we can use to force our system into a desired state.
Spy Objects – Are types of Dummy object that allow us to track when something was called on them.
Mock Objects – Are types of double object which expose our properties in such a way that show a ‘behavioural surface area’.
Fake Objects – Are types of object that contain ‘fake’ business logic. They can be used in places where complexity needs to be mimicked.

We also learned that a ‘Mock object’ should not be confused with a ‘Mocking framework’. A mocking framework will allow us to dynamically generate all manner of Test Doubles.

This picture should help with keeping the types of doubles and their relative spacing to each other in mind.

Test Doubles
Test Doubles

Try to aim to always use the simplest possible type of Test Double for the job. This blog has ordered the doubles in their relative complexity. Using Fake objects will be fraught with problems, they will almost definitely have bugs in themselves so use with extreme caution.

You can learn more about test doubles here…

The little mockist – Uncle Bob

Test Doubles – Martin Fowler

$httpBackend Enhances Test Driven Development in Angular

In this blog post we will examine the $httpBackend object and how it really helps us to write clean and maintainable unit tests when practicing Test Driven Development (TDD).

I’m a practitioner of Test Driven Development. If you have read my e-book you can see that I am keen on applying the 80/20 rule to automated testing and creating unit tests that work like behaviour tests. This means that in my tests I recommend using the applications’ own API to physically set pre-conditions of a test.

However, in pure vanilla Javascript this can become quite cumbersome and brittle using only pure callbacks. Take, for example, the following test code…

This test code explains an object called the ‘RouterWizard’. It is a component which shows a progress indicator on some forms a user needs to fill out. The user can ‘step back’ or ‘progress’ through the screens. The code above does 3 things…

  1. (Line 4) – Firstly it spies on the ‘$http’ . ‘delete’ function
  2. (Line 6) – Invokes a function called ‘back’ on the ‘RouterWizard’
  3. (Line 6 – 10) – It will execute a callback when ‘RouterWizard’ has finished

The final callback (Lines 6 – 10) should be called when the ‘RouterWizard’ has finished executing but because of it’s functional nature this unit test could exit before this final callback has had a chance to execute. This could lead to a false positive (which you really really want to avoid at all costs when automating testing). The initial solution is to inject a ‘done’ function into the test (which will force the test to fail if it never completes), for example…

This works by telling the test framework (in this case Jasmine) to inject a function into the test which will guarantee is called before declaring the test finished. If it never get’s called the test will fail after a set period of time!

Enter the $httpBackend object

Whilst the previous code is an improvement and fixes the potential false positive issue on our first example this is still fairly ugly, and if we are to be great developers then we don’t write ugly code!

Ok, so at the moment we only have one callback and so isn’t too ugly, but as I said, we may be writing behavioural tests with complex set up and multiple callbacks. The result will be deep and confusing callbacks. It’s really important that the tests are clean and easy to understand (critical in fact). So Angular comes to the rescue with the $httpBackend object.

As you can see the $httpBackend is an object that is using a reference to an internally stored collection of asynchronous calls, it is overwriting these with test doubles. Then it is executing them synchronously thus blocking the test there and then, and making sure all of the fake backend calls are complete, it does what is says on the tin; it flushes. Since we aren’t actually performing IO in this test we don’t need to worry about blocking the process so can make the code halt whilst it is being flushed.

This diagram is handy to refer to to get the process that the $httpBackend object goes through when the test code invokes it.

$httpBackend for Test Driven Development in Angular
$httpBackend for Test Driven Development in Angular


Using $httpBackend.flush has the clear benefits of allowing us to stay out of callback-spaghetti-hell and is truly brilliant for making test code nice and easy to read! Angular has other great testing features but this is just one very powerful one.

There we have it, possibly the best feature in Angular for me. When I was a Javascript baby my tests were always just too spaghetti like now they read much easier thanks to this brilliant feature. Thanks Angular!