A Spock Tutorial for Javaer
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.
Comparision
- JUnit, testNG
- Cucumber(Gherkin). “one file solution”
- Java BDD framework, like: JBehave
- RSpec spock/issues/106
Spock Quick Start
pom.xml:
1 | </dependencies> |
Usage Example
Blocks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15def "events are published to all subscribers"() {
given:
def subscriber1 = Mock(Subscriber)
def subscriber2 = Mock(Subscriber)
def publisher = new Publisher()
publisher.add(subscriber1)
publisher.add(subscriber2)
when:
publisher.fire("event")
then:
1 * subscriber1.receive("event")
1 * subscriber2.receive("event")
}
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 | str == "content" // assert the equality between strings |
1 | publisher.subscribers << subscriber // << is a Groovy shorthand for List.add() |
see also:
groovy-lang.org/syntax.html
some demos
Exception Conditions
thrown, notThrown
1
2
3
4
5
6when:
stack.pop()
then:
thrown(EmptyStackException)
stack.empty
Support Java Testing Lib
including JUnit, Mockito, JAssert, Hamcrest, etc.
Data Tables
A awesome feature!
1 | class MathSpec extends Specification { |
Data Pipes
1 | ... |
Migration from Java to Groovy
java lambda expression vs groovy closure
java:
1 | () |
groovy:
1 | {} |
[] vs {}
java:
1 | (classes = {A.class, B.class}) |
groovy:
1 | class, B.class]) (classes = [A. |
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:
public MyRule rule = new MyRule()
// doesn't work (with static modifier):
public static MyRule rule = new MyRule()
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!