Monday 4 June 2012

Testing legacy code with Mockito spies

When we're working with legacy code, before making any changes we should write unit tests that will prevent us from breaking existing functionality. However most of the time, writing tests for legacy code is not easy.

Let's take a look at a simple example, that will try to show the challenges that we may face:

We have a class that calculates a discount for a customer based on his name and the amount of product that he's buying.

The problem hides in a static method call CustomerService.isImportantCustomer(). In the old code we can see a lot of static methods. Let's say that the one in our example is calling the database.
We need to mock it in order to write a proper unit test.

First of all, we will extract the static call to a separate method:

Refactoring using IDE (extracting methods, renaming etc.) is considered to be safe. Once we did that we can use a nice feature of Mockito - spies. 
If we declare our tested class as a spy, we can mock its method the same way as with standard mocks. The test for our class could look like:

The Mockito API for spies is similar to the one for mocks (the syntax is different for overriding void methods).

No comments:

Post a Comment