Despite JUnit’s popularity, Spock is sometimes recommended as a “better” alternative for writing tests in Java projects. It’s usually sold as a clean, one-size-fits-all solution which will magically make your tests more readable and easier to write. I disagree with those claims; having tried it on several projects, I find it to be a much more confusing and restrictive framework.
In this post I hope to convince you to stick with JUnit for your upcoming project.
If you prefer Groovy to Java, my aim is not to disparage your choice, but rather to highlight that mixing those two languages makes for a worse software writing experience.
It’s not Java
When writing tests in Spock, you write them in Groovy. It’s technically “Java-syntax compatible”, but, ultimately, you’re supposed to write things “the Groovy way”. I would argue that code like list.findAll { it % 2 } or thing.do() >> something is not going to be immediately understandable to most Java developers, let alone any non-technical stakeholders who might have otherwise benefited from a documentation-as-tests approach.
Groovy does offer some appealing syntactic sugar such as ?. which seems nice. However, there’s a reason that production code is done in Java and not Groovy. This was a (hopefully) deliberate choice that weighed the pros and cons of both languages. Personally, in the Java vs Groovy debate, I’m firmly on the side of Java, as is most of the industry. I don’t see why we should apply a different standard to test code.
It’s less readable
Spock generally wins in terms of the short length of test code (though there are caveats to it). However, short does not mean more readable. In many cases it can mean the opposite.
Domain-Driven Design and BDD suggest writing tests that could, with some guidance from the developer, be understood by business. This not only promotes writing readable tests, but also enhances collaboration.
0 * _._ is a perfectly valid assertion in Spock. I would not feel comfortable writing this, let alone showing this to anyone less than incredibly tech-savvy. Other examples of assertions promoted by the Spock documentation are _ * auditing._ and 1 * subscriber._(*_).
In JUnit (with Mockito), these, more or less, translate to things like:
verifyNoInteractions(someParticipant1, someParticipant2); verify(auditing).someMethod(); verify(auditing, times(1)).someMethod();
These are not exact translations, but I don’t believe the Spock versions are all that useful to begin with.
To further illustrate my point, consider these two tests:
def "test 1"() {
given:
List<String> valueParts = ["a"]
SomeDependency dependency = Mock()
dependency.produceValue() >> valueParts.join("")
when:
valueParts.add("b")
then:
dependency.produceValue() == "ab"
}
def "test 2"() {
given:
List<String> valueParts = ["a"]
SomeDependency dependency = Mock()
dependency.produceValue() >> { valueParts.join("") }
when:
valueParts.add("b")
then:
dependency.produceValue() == "ab"
}
Both of these tests are valid Groovy/Spock and both will compile. However, in my opinion it’s far from obvious why the first test will fail. Mockito, for its part, clearly separates the two functionalities (static return and dynamic answer) into thenReturn and thenAnswer, so that a developer must intentionally choose to use one or the other.
It lacks compile-time safety
Let’s say I made some changes to my code and my class no longer has a method called doThing(), which is still being referenced in other parts of the codebase:
new SomeClass().doThing() // Wants to call doThing()
class SomeClass {
// Does not have doThing() method
}
If this was Java, I would get errors in the IDE for every single usage of doThing(), and compile-time errors. This makes it easy to quickly fix the usages, as you can just go down a list. In Groovy, the IDE stays mum until it gets to the broken line at runtime. Only then does it fail with MissingMethodException. If you were using doThing() extensively in your tests, you now potentially have to run your entire test suite each time you fix a single usage to find the next line to fix.
The same is true when you accidentally pass an incorrect type as an argument:
int notString = 12
doThing(notString) // This will compile, but fail at runtime
void doThing(String string) {
// ...
}
In both cases IntelliJ does add a little squiggly underline to indicate a warning. This, however, is much less useful than how it treats Java errors.
For a more insidious example, consider this piece of code:
record SomeVo(String value) {}
record SomeWrappingVo(SomeVo value) {}
class SomeClass {
static final SomeWrappingVo WRAPPING_VO = new SomeWrappingVo((SomeVo) VO) // Passing VO before it's initialized
static final SomeVo VO = new SomeVo("SomeValue")
}
println(SomeClass.WRAPPING_VO)
This will not only compile, it will run. The only problem is that the printed value will be SomeWrappingVo[value=null], instead of the expected SomeWrappingVo[value=SomeVo[value=SomeValue]]. For comparison, the Java equivalent would have failed at compile-time with “illegal forward reference”.
It’s unpredictable
Example 1
The simplest example I can give is this test:
def "some test"() {
given:
String string1 = "Some string"
then:
string1 == string1
}
It will not work, failing with:
Groovyc: 'then' is not allowed here; instead, use one of: [and, expect, when, cleanup, where, end-of-method]
It turns out that “given … then …” is not valid in Spock, even though “given .. when … then …” is. If you omit when, you must use expect instead of then.
Example 2
Another example of Spock’s unpredictability is writing a deliberately failing test stub. Sometimes I want to write out all of the things I want to test before I actually implement the tests. In JUnit, I can just put any assertion that will fail inside of the test stub:
@Test
void shouldFail() {
// Any one of these will work:
fail("Not implemented yet");
assertTrue(false);
assertThat(true).isFalse();
}
It would stand to reason that I could do something similar in Spock, e.g.:
def "should fail"() {
true == false
}
Unfortunately, Spock will not even discover the test above. The first thought could be that I’m missing the required given, when, then blocks. However, here’s a version that actually works:
def "should fail"() {
expect: false
}
I realize that expect is just another block in Spock. However, it’s another thing that you “have to know”. I don’t feel like these blocks help me write better code. I feel like I’m limited and constantly surprised by them, despite being a big fan of the “arrange-act-assert” approach.
Example 3
At some point I had a Controller calling a Use Case in my code. The test for it looked something like this (simplified example):
when:
controller.send("someArgument")
then:
1 * subscriber.doThing("someArgument")
I needed the Use Case to return some information to the Controller, so at some point I ended up with transitory test code like this:
given:
useCase.doThing("someArgument") >> "someResponse"
when:
controller.send("someArgument")
then:
1 * useCase.doThing("someArgument")
I was surprised to see that this test did not pass even though I added the required functionality in the production code. I spent a significant amount of time debugging my arguments (“Is there an equals() missing somewhere…?”), only to find a StackOverflow answer pointing to the documentation.
It turns out that “when mocking and stubbing the same method call, they have to happen in the same interaction”. Otherwise the mocking just doesn’t work. I would argue this firmly violates the Principle of Least Astonishment.
Example 4
Another example is the requirement for prefixing assertions with assert. Take this test, for example:
def "should add one"() {
given:
int a = 1
when:
a = a + 1
then:
a == 2
}
I didn’t need to add assert before a == 2. However, if I extract the assertion into a method:
def "should add one"() {
given:
int a = 1
when:
a = a + 1
then:
equalsTwo(a)
}
private static void equalsTwo(int a) {
a == 3
}
…Then the assertion no longer works. You can tell, because now I’m asserting that a equals 3, and yet the test passes.
However, if I wrap the assertion in with(), then the test starts asserting properly again:
def "should add one"() {
given:
int a = 1
when:
a = a + 1
then:
equalsTwo(a)
}
private void equalsTwo(int a) {
with(a) {
it == 3
}
}
Notice, though, that I had to make my equalsTwo() method non-static – with() won’t work with static methods…
Example 5
Yet another example is this test:
def "some test 2"() {
given:
SomeClass someMock = Mock(SomeClass) // Pretend this is not the SUT
String string1 = "Some string"
when:
someMock.doThing(string1 + " modified") // Pretend this happens in the SUT
then:
String expectedString = "Some string modified"
1 * someMock.doThing({
it == expectedString
})
}
When run, it gives the following error, suggesting that expectedString was not defined:
Too few invocations for:
1 * someMock.doThing({
it == expectedString
}) (0 invocations)
Unmatched invocations (ordered by similarity):
1 * someMock.doThing('Some string modified')
One or more arguments(s) didn't match:
0: Condition failed with Exception:
it == expectedString
| |
| groovy.lang.MissingPropertyException: No such property: expectedString for class: com.example.SomeTestClass
| // Stack trace omitted for brevity
Some string modified
“Too few invocations” for someMock.doThing? But it’s invoked right there in the test! It turns out that the “fix” is to move the definition of expectedString from the then block to the given block, at the expense of readability:
def "some test 2"() {
given:
SomeClass someMock = Mock(SomeClass) // Pretend this is not the SUT
String string1 = "Some string"
String expectedString = "Some string modified" // Moved from 'then' block
when:
someMock.doThing(string1 + " modified") // Pretend this happens in the SUT
then:
1 * someMock.doThing({
it == expectedString
})
}
The error message is particularly cryptic – you just have to know that you’re not allowed to define variables in the then block (the documentation explains this by stating that internally Spock moves some of your code around to earlier blocks, which itself does not sit right with me). It turns out, however, that you can define variables in the then block if you wrap both the definition and the assertion in an interaction {} (as long as you don’t extract the interaction {} into a method). It’s not something the error will tell you, though.
Example 6
With more complex tests (e.g., acceptance tests), it’s sometimes a good idea to create a “test driver” class which provides a higher-level abstraction over actions, hiding complex test double instrumentation behind them. It turns out that, while this is perfectly acceptable in Spock:
class TestSpec extends Specification {
def "test"() {
given:
TestService testService = mockIt()
when:
String result = testService.getThing()
then:
result == "test"
}
TestService mockIt() {
TestService testService = Mock(TestService)
testService.getThing() >> "test"
return testService
}
interface TestService {
String getThing()
}
}
Extracting mockIt() to another class will not work:
// ...
class TestSpec extends Specification {
def "test"() {
given:
TestService testService = new TestServiceMocker().mockIt()
// ...
}
static class TestServiceMocker { // Not possible
TestService mockIt() {
TestService testService = Mock(TestService) // Mock not available here
testService.getThing() >> "test" // Throws "java.lang.NullPointerException: Cannot invoke method rightShift() on null object" if DetachedMockFactory is used above
return testService
}
}
// ...
}
As far as I know, not even using a DetachedMockFactory can make it work. This severely limits the possibilities of cleaning up setup code, as every single mock must be explicitly setup within the Specification class.
Example 7
Due to the lack of compile-time safety, combined with how obscure the inner workings of Spock are, it’s very easy to accidentally write tests that only pretend to work. A real-life example I encountered is the following test:
def "should only pass a single-element list to TestService"() {
given:
TestService testService = Mock()
when:
testService.doThing(["someValue1", "someValue2"])
then:
1 * testService.doThing(_ as List<String>) >> { List<String> values ->
assert values.size() == 1 // Should fail
}
}
interface TestService {
void doThing(List<String> value)
}
It looks like it should work (unless you’re a vigilant Spock expert). It compiles, runs… and passes. It turns out that values is a List<List<String>>, instead of the List<String> that the test expects. It contains a list of all arguments passed to the method. However, the same pattern works if the argument is not a list:
def "should pass a specific value to TestService"() {
given:
TestService testService = Mock()
when:
testService.doThing("someValue")
then:
1 * testService.doThing(_ as String) >> { String value ->
assert value == "someValue" // Will pass
assert value != "someValue" // Will fail
}
}
interface TestService {
void doThing(String value)
}
Again, you could argue this is user error, but I’d argue it should not be possible to make a mistake like this.
Less reproducible examples
An intermittent issue I get is the debugger behaving erratically, e.g., showing incorrect values for variables, or stepping into a method and immediately throwing in another, seemingly unrelated one. While these could again be chalked up to the tooling not being mature, it’s still a problem for me (and the tooling did have many years to mature, after all).
While I was unable to create an easily reproducible example, Spock often fails me in terms of error messages and defect localization, i.e., it shows the wrong line failing with an error message so cryptic I don’t even know where to start debugging. This is likely due to the lack of compile-time safety – the most recent example of this was me forgetting to return this from a fluent method, with Spock producing a Condition not satisfied error with a very long list containing the toString() result of each return of a long fluent chain. It also didn’t help that the list was over ten screens wide.
There’s more of these “things you just have to know” in Spock, and that’s not something I ever had to deal with when using JUnit.
JUnit extensions are easier to understand and use
While this is, of course, subjective, my first experience with JUnit extensions was much smoother than with Spock.
I frequently use the JUnit extension mechanism for test templating, or automating things that should happen between tests (such as initializing some object and injecting it into a test via a parameter, or automatic context cleanup). There are some well-named interfaces for this, such as BeforeAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver, among others. I was able to figure out how they work without having to read any external documentation.
Spock has IAnnotationDrivenExtension, with a bunch of default methods such as visitSpecAnnotation, visitFieldAnnotation, visitFixtureAnnotation, each also having a plural equivalent. Perhaps to some it is clear what they do, how they work, and how to achieve the things I described in the previous paragraph. For me, they’re just complicated. I understand from looking at the Spock code that I’m meant to add interceptors somewhere to achieve my goals. I could just implement an interface in JUnit, though.
IDE support is poor
Using Spock in my Java projects has been a headache when it comes to support within the IDE, specifically IntelliJ. As an example, even “extract method” doesn’t reliably allow me to extract parts of code:

Sure, maybe that one’s on Jetbrains, and not on Spock/Groovy. However, the issue is very much real for someone who has to use those technologies at work – pointing fingers won’t do me any good when I can’t do my job.
Anything I can do in Spock, I can also do in JUnit
These days there is nothing that can be done in Spock that can’t also be done in JUnit with Mockito and AssertJ – be it parameterized/data-driven tests, complex mocking, BDD-style tests, or rich assertions. From a personal point of view, I would argue that the JUnit side does them better.
The only exception to that is data-driven tests written as tables, but those tend to be abused into horizontally-scrolling monstrosities, so I’m glad for their absence.
Moreover, JUnit has some features that Spock is lacking, such as grouping tests using the @Nested annotation.
Parallel testing seems to be an afterthought
With JUnit Jupiter, I can easily configure parallel test execution to only be enabled for unit tests (and not integration tests), by adding junit.jupiter.execution.parallel.enabled=true to an execution of Maven’s surefire, leaving integration tests to be executed sequentially by failsafe. I can then use a simple naming scheme (*Test vs *IT) to distinguish between both types of tests.
To enable parallel execution in Spock, it seems the only solution is to create a SpockConfig.groovy file which will enable parallel execution based on an environment variable. While this will work in CI, the IDE will get confused when it runs the tests, as it doesn’t know how to account for a custom system variable. In the case of IntelliJ, I’ve run into a problem where it sees my custom runSpockInParallel system property variable in maven-surefire-plugin, so it decides to add it to all tests, breaking my integration tests.
This could be solved by SpockConfig.groovy having an additional property to specify which tests should be parallelized, but currently nothing like that exists.
Perhaps there is a better way to only run some Spock tests in parallel, but it doesn’t seem to be documented anywhere.
Conclusion
The most common benefit of Spock that I always hear is that the tests are shorter than when using JUnit. However, the amount of characters is the wrong metric to optimize for. I insist that verbosity is important if the alternative loses readability – writing shorter tests is a self-defeating exercise if those shorter tests are harder to understand.
Furthermore, a test framework so unpredictable that you need to actively consult its documentation is not a good choice for complex projects. When writing Spock tests, I find myself constantly questioning if the test I’ve written is “correct” and if it will even verify the conditions I’m trying to assert.
Perhaps for some writing Spock tests is a wonderful experience once you fully understand all of the intricacies of both it and Groovy (however long that might take). Unfortunately, the above was my frustrating experience with it as a Java developer, across more than one project.
For Groovy projects, Spock may be a great choice. For Java projects, however, I see more downsides than benefits when it comes to ditching JUnit.
Be First to Comment