The song of the mockingbird

I have a new favourite drink: Mockito!

For my Computer Science thesis, I worked with the annotation processing framework of the java compiler. It is actually a pretty cool framework that allows you to extend the compiler by processing annotations at compile time, and it can be set up to work simply by including a jar on the classpath. The API is actually pretty nice, using fancy stuff like  mirror-based reflections and whatnot. But it was a pain in the ass to unit-test. As my components lived in the middle of a compiler pipeline, there was a huge environment of objects that it assumed the existence of, and while the courses i took on test-driven development taught me to use a test stub to factor out components that I wasn’t testing, it just seemed like an overwhelming task in this case. So I created a lot of Java source code and wrote some jUnit-fu to turn it into test cases for my compiler extention. It wasn’t pretty, but it got the job done.

Now, imagine my joy, and the feeling of facepalm, when I started in my new job, opened up the relatively new Java codebase and discovered the concept of a mocking framework! The ability to hot-swap objects with mocks that just returns whatever you tell them to does not sound like such a big deal until you’ve tried to test small components in a big world, but boy, does it change the way testing works.

To those who unit-test and haven’t yet tried a mocking framework, I urge you to try it out. It works particularly well with some sort of dependency injection scheme, as you can mock the dependency injection and through that inject your mock objects whereever you want them. As for frameworks, I have only personally tried Mockito, but there are several out there, all with strengths and weaknesses.