Friday, February 13, 2015

Mocking and Stubbing and using PowerMock

Unit testing  is when developers adhere to a practice of testing units of code. There are many benefits in writing unit tests, specially when it is done in TDD (Test Driven Development) as an agile practice. However in this article I am not going to describe the many benefits of unit testing as that information is already flooding the internet.  Even though Martin Fowler, in his article  explains the differences between Test Doubles (Mocks, Stubs, Dummy and Fake Objects), in this article I intend to focus on the subtle difference between Stubbing and Mocking.

My understanding is that Mocks and Stubs are there to eliminate testing all the dependencies so that it would be easy for us to focus on the unit of code that we want to test. Which means that these dependencies are either mocked or stubbed.

The main difference between mocking and stubbing to me is that, when Mocking we pre-program behavior.  Basically we have the flexibility to tweak the behavior or create our own expectation on how the collaborating classes should behave for every scenario that we want to test.
This means that when mocking, during verification stage we get to perform behavior verification.  i.e we ensure that  "class under test" would make the  correct calls to the collaborating classes,in a fashion that we have defined.  

Stubs:  are also already pre-programmed code as well; but they have a fixed response.  However in Martin Fowler's, assay, it is mentioned that Stubs can also perform behavior verification. They are known as spy objects.

According to this Vedio; basically you can clearly differentiate a Mock from a Stub , is when you know that Mocks do verification of the interaction. Stubs simply are just used for faking.

In most legacy systems, and to my experience I have come across many tightly coupled code with legacy system frameworks. Code that has been so tightly coupled that it sometimes makes the code truly untestable. 
I found Powermock a useful library for unit testing, as it has the facility to mock static, and private methods as well. Please checkout my github repository here.