Tuesday, August 30, 2011

Testing Concrete Methods in Abstract Classes... With Mockito

There will probably come a time, especially if your life is TDD, that you will need to unit test an abstract class. More specifically, a concrete method in an abstract class. The standard response is, you should create a test implementation (a mock implementation) of that abstract class and then run your tests against that. However, if you're like me, then this smells wrong.

  1. If the structure of the abstract class changes in the future, then you'd need to update this test implementation. This is unnecessary maintenance. 5 years ago, there was argument for building out an extensive object-mocking library in your code, but there is just no reason anymore.
  2. The object creation code itself takes away from the simple readability a test should have. Each test should read like a note about the code it's testing: "You know I've been thinking, given that a car is blue, when that car is being driven, then the car description should also say that it is blue". Not "You know, given that a car is blue, when that car new blueCarImp class extends Car getColor return super getColor 01000110 OMG WHAT JUST HAPPENED TO MY CAR" (I realize that you can have a mock object existing somewhere else and instantiate that object, however that has the smell of not keeping all test related code inside of or close to that test. Also see #1).
This is where Testing Frameworks come to the rescue.

At MagnetStreet, we use Mockito. I've use a few different testing frameworks, and this is by far my favorite for being the most readable. The only problem is, when you mock an abstract class in mockito, it will stub out the method you want to test. So, if you do some searching around, you'll see people recommend using the spy ability. It can be even easier. Without any more drama, here's the solution:

No comments: