Art Of Unit Testing - Book Wiki > Chapters > 3. Using Stubs to Break Dependencies

3. Using Stubs to Break Dependencies

Starting Paragraph

In the previous chapter we took a stab at writing our first unit test using NUnit, and explored the different kinds of attributes that are available to us as a test developer such as ExpectedException, SetUp, and TearDown. We also built tests for very simple use cases, where all we had to check on were simple return values from simple objects.  

In this chapter we’ll take a look at some more real world examples where the object under test actually relies on another object over which we have no control (or it does not work yet). That could be a web service, the time of day or threading, or many other things – the important point is that our test will have a hard time to control what that dependency returns to our code under test. That’s when we use stubs.  

One of the most difficult tasks man has created is flying people to outer space. It brings interesting challenges to the engineers and astronauts, one of the more difficult ones being how you make sure you’re ready, as an astronaut to go into space and operate all the machinery.   

Obviously you can’t do a full on integration test for a space shuttle to find out if the astronauts do their job right, let alone simulate problematic situations. That’s why NASA has full simulators that mimic the surroundings of a space shuttle control deck, thus removing the external dependency on having to be in outer space.  

Space is a good example of what this section and most of this book will be dealing with – how do you control external dependencies in your code so that it would be easier to do things with it (like testing it).  

If you take this notion of replacing something with something into the world of unit testing, that something is called a stub. Let’s define that concept.  

Stub: Definition  

A stub is a replacement for an existing dependency in the system, which your test can have control over. A stub will help you test your code without dealing with the dependency directly.  

Definition: External Dependency  

An external dependency is an object in your system which your code under test interacts with, and over which you have no control (File System, Threads, Memory, time etc..)  

  

So let’s make things a bit more complicated for our LogAnalyzer by trying to untangle a dependency against the file system, as our next section describes.

   

Comments? Errata? 

   

Tag page
You must login to post a comment.