The difference between mocks and stubs

Within the field of unit testing, we use “mock objects” (see also one of my previous posts) and “stubs” to help us testing our classes. For example when having a class which writes directly to a piece of hardware, and you want to write a unittest for it, you have to create some stand-in class which operates like this device. This is needed since the device isn’t really there when running the tests on a build machine. Also, we probably want to force our device in some state or want to get rid of time constraints. Since many people actually don’t know the difference between a stub and a mock, you can take the following rule of thumb about the difference between mocks and stub:

  • With mocks you can control the flow of your object. You can for example call a mock instance which will react the same as if you would interface with a real piece of hardware but without the need of the hardware of having to deal with time constraints.  With a mocking framework you are be able to influence the behavior of the object you have mocked.
  • Stubs normally return a default value. For example they return always true when calling a method which has a return value.

So in short: if you won’t want to control the behavior of your object, you want to write a stub. Otherwise you write a mock object for your unittest.

Posted in TDD at February 17th, 2013. 1 Comment.