Thursday 8 December 2011

Mockito mysteriously not mocking

Mockito mysteriously not mocking

This may sound familiar to you if you have worked on a large software project which was not previously designed with mocking in mind. I'm working on one of those at the moment and decided to get Mockito involved to make the testing more sane.

The legacy code was not designed with unit testing in mind, and as such a lot tightly coupled business logic has been pushed higher up the inheritance stack to make it available to more classes. We have been attempting to refactor the code base so it is more testable, but there is little appetite for major changes, and a number of customer deadlines are holding up this refactoring work.

Meanwhile we still need to write unit tests, and Mockito has proven useful in testing everything except classes from the main inheritance stack (we call them Business Objects).

Recently I read this excellent article on spying. Which allows you to change the behaviour of a real instance of a class with some mocked behaviour. Sure, this approach isn't pleasant and its code smell for the larger problem of poor architecture and design. However, it does work.

We found the one thing we couldn't do was mock/spy on methods higher up the inheritance chain, and were unable to work out the reason for this.

Turns out other people are having this problem as well.

Its not pretty, but it works in our case. Make all classes in the inheritance hierarchy public.

References:

No comments:

Post a Comment