Wednesday, March 21, 2012

Spock - the testing as it should be done

It's not very often when I get really excited about some piece of software. I'm not saying it doesn't happen because that wouldn't really be true but those times when I get the willies just after taking a brief look at something are really rare. Today is that day. Today I met Spock.

Well technically speaking, I met this guy, Luke Daley, on 33rd Degree conference when he gave a talk about Spock and how it differs from what you can do with regular JUnit tests.

OK. Enough of about the conference - let's see some code!


If you put this into an example.groovy file and execute it it'll actually run 2 unit tests. On the test we see the following sections:

  • We see that Spock is being grabbed (excluding Groovy since Spock tries to pull in some non-existent version)
  • We then create an Example Specification (that's how you should read the class declaration line)
  • We then say that we define that a sum of a and b is equal c (whatever those are)
  • Then some magic happens: we say that we expect that a + b is equal to c
  • And last but not least we define the set of data to create separate tests in a tabular, fitness-like form

Here's the output of that script (you should run it yourself to see it really do all the work!):
JUnit 4 Runner, Tests: 2, Failures: 0, Time: 15
Isn't it great? You spent about no time creating a few lines of code, got 2 test cases in return that execute in no time and are no match for JUnit's @Parametrized tests (which sucks big time by the way).

This is obviously the absolutely simplest example possible. There's a lot more to Spock than meets the eye here and the deeper you go there the more you wonder how's all that even possible. This is why I'll stick to Groovy as the most versatile, universal, non-problematic and powerful language ever created for the JVM.

2 comments:

Tomek Cejner said...

I must admin that once I saw spock in action, I see no reason to use JUnit :]

Steve said...

Cool beans - thanks!