A Spock Tutorial for Java Developers
A Spock Tutorial for Java Developers
What is it?
The description of its github repository:
The Enterprise-ready testing and specification framework.
A Quote from the office website:
Spock is a testing and specification framework for Java and Groovy applications.
What makes it stand out from the crowd is its beautiful and highly expressive specification language.
Thanks to its JUnit runner, Spock is compatible with most IDEs, build tools, and continuous integration servers.
Spock is inspired from JUnit, RSpec, jMock, Mockito, Groovy, Scala, Vulcans, and other fascinating life forms.
Spock Framework Reference Documentation
Advantage
Specifications as Documentation (BDD);
given-when-then
; generating-report.less code, more readable, some awesome feature:
- blocks, (no)thrown, ‘==’,
- where, table, database,
- with, verifyAll
- more fluent Mock syntax
support
JUnit
, it’s suppot all@Rule
s in JUnit.
Comparison
- JUnit, testNG
- Cucumber(Gherkin). “one file solution”
- Java BDD framework, like: JBehave
- RSpec spock/issues/106
Spock Quick Start
pom.xml:
1 |
|
Usage Example
Blocks
1 |
|
Conditions
Within the then
and expect
blocks, assertions are implicit
some Shorthand (syntactic sugar in Groovy)
The test code wrote by Spock are more concise and easier to read.
There’s less clutter, boilerplate code, and your test cases can be structured better.
e.g:
Java’s == is actually Groovy’s is() method, and Groovy’s == is a clever equals()!
1 |
|
1 |
|
see also:
groovy-lang.org/syntax.html
some demos
Exception Conditions
thrown, notThrown
1 |
|
Support Java Testing Lib
including JUnit, Mockito, JAssert, Hamcrest, etc.
Data Tables
A awesome feature!
1 |
|
Data Pipes
1 |
|
Migration from Java to Groovy
java lambda expression vs groovy closure
java:
1 |
|
groovy:
1 |
|
[] vs {}
java:
1 |
|
groovy:
1 |
|
groovy handy no-setter (or no-getter) syntax
declare a field without access modifier
Precaution
- IntelliJ-IDEA: must set test directory otherwise it reports
Empty Test Suite
error.
- JUnit
@ClassRule
1
2
3
4
5
6
7
8
9// it works:
@ClassRule
@Shared
public MyRule rule = new MyRule()
// doesn't work (with static modifier):
@ClassRule
@Shared
public static MyRule rule = new MyRule()