Updated: Jun 18, 2018
At Wix, we make extensive use of the Specs² testing framework. It has become the standard tool for writing software specifications in our backend group, replacing JUnit, Hamcrest and ScalaTest. We have always been highly fond of matchers, having adopted Hamcrest back in 2010, and our testing methodology has developed to heavily rely on matchers. We went as far as writing a small utility framework, back in our Java days, that takes an Interface and creates a matcher from it using JDK Proxy. For a class Cat with fields age and name, the interface would basically look like this:
Which then would’ve been used like this:
As you can see, this involves a fairly large amount of boilerplate. Moving to Specs², we wanted to keep the ability to write matchers for our domain objects. Sadly, this didn’t look much better written using Specs² matchers:
What quickly became apparent is that this calls for a DRY approach. I looked for a way to create matchers like these automatically, but there was no immediate solution for implementing this without the use of compiler-level trickery.
The breakthrough came when we hosted Eugene Burmako during Scalapeño 2013. I discussed the issue with Eugene who assured me that it should be fairly easy to implement this using macros. Next, I asked Eric, the author and maintainer of Specs², if it would be possible for him to do that. Gladly, Eric took the challenge and Eugene joined in and helped a lot, and finally, starting with version 2.3 of Specs², we can use macros to automatically generate matchers for any complex type. Usage is fairly simple; you need to add the Macro Paradise compiler plugin, then simply extend the MatcherMacros trait:
This would be the place to thank Eric for his hard work and awesomeness responding to my crazy requests so quickly. Eric, you rock.
This post was written by Shai Yallin
You can follow him on Twitter