Java Reference
In-Depth Information
1*spock.soothe()
}
There are two ways to use the
Mock
method in Spock. The first is shown here: instantiate
the class, and assign it to a variable of the proper type. The method will implement the in-
terface of the declared type. The second way is to use the interface type as an argument to
the
Mock
method, which isn't shown here.
Once the mock has been created, the
when
block uses the mock as the argument to the
react
method. In the
then
block, first the proper reaction is checked, and then comes
the interesting part. The last line says that the test passes only if the
soothe
method is
called on the mock exactly one time, ignoring any returned value.
This is a very flexible system. The cardinality can be anything, including using an under-
score as a wild card (for example,
(3.._)
means three or more times).
Moving on to the
Klingon
interface, the following test does multiple checks:
def "reacts badly to Klingons"() {
Klingon koloth = Mock()
when:
String reaction = tribble.react(koloth)
then:
1 * koloth.annoy() >> {
throw new Exception()
}
0 * koloth.howlAtDeath()
reaction == null
Exception e = thrown()
}
checks to see that the
annoy
method on the mock is invoked exactly once and, using the
right-shift operator,implements themethod bythrowinganexception. Thenextline checks
that the
howlAtDeath
method is not invoked at all. Because the
annoy
method throws
an exception, there is no returned reaction. The last line then verifies that annoying the
Klingon did in fact throw the expected exception.
25
How do you mock a Klingon? From a galaxy far, far away (rimshot).