Unit Tests

What is a unit test?

Takes a very small piece of testable code and determines whether it behaves as expected. The size of the unit under test is not strictly defined, however unit tests are typically written at the class level or around a small group of related classes. The smaller the unit under test the easier it is to express the behaviour using a unit test since the branch complexity of the unit is lower.

If it is difficult to write a unit test, this can highlight when a module should be broken down into independent, more coherent pieces and tested individually.

Unit testing is a powerful design tool in terms of code and implementation, especially when combined with TDD.

What can/should you unit test?

  1. Test the behaviour of modules by observing changes in their state. This treats the unit as a black box tested entirely through its interface.
  2. Look at the interactions and collaborations between an object and its dependencies. These interactions and collaborations are replaced by mocks/stubs etc.

Purpose of unit tests

  • Constrain the behaviour of the unit
  • Fast Feedback



TDD (test driven development) and BDD (behaviour driven development) are usually used hand in hand in an agile environment. However, sometimes it seems like they are used in a way that they mean the same thing which is not true. TDD/BDD what’s the difference eh? Well, to me here it is:

TDD – the focus of writing and making tests pass in the implementation phase helps make the development process faster and more efficient (in terms of faster and useful feedback). Always write tests first when you can (sometimes it is difficult to write tests or it may not make sense to test something so small – I will write another blog post about this).

BDD – real user behaviour and interactions drive tests and development. You are focused on what the user does, whoever the user may be. You will consider the standard user on one end and the extreme user on the other (i.e. someone who will click every button on your site or do strange things like doing a GET on a URL that should only be doing a POST).