Spock testing : cleaning after "where:" block finishes
16,663
Solution 1
You can have a cleanup block in your method like so:
@Unroll
def "a method that tests stuff"(){
given:
def foo = fooDAO.save(new Foo(name: name))
when:
def returned = fooDAO.get(foo.id)
then:
returned.properties == foo.properties
cleanup:
fooDAO.delete(foo.id)
where:
name << ['one', 'two']
}
The "cleanup" block will get run once per test iteration.
Solution 2
If you use @Unroll
, then cleanup:
will be called for every entry in the where:
block. To only run cleanup once then move your code inside the def cleanupSpec()
closure.
@Shared
def arrayOfIds = []
@Unroll
def "a method that tests stuff"(){
given:
def foo = fooDAO.save(new Foo(name: name))
when:
def returned = fooDAO.get(foo.id)
arrayOfIds << foo.id
then:
returned.properties == foo.properties
where:
name << ['one', 'two']
}
def cleanupSpec() {
arrayOfIds.each {
fooDAO.delete(it)
}
}
Author by
Shay
Updated on June 22, 2022Comments
-
Shay almost 2 years
I have 2 test methods .
They all execute each line of the where block, I need a cleanup for add & relax methods.
I've tried cleanup block , void cleanup() , def cleanupSpec() , non suits .
How can I explicitly run a cleanup after specific method which have "where:" block?
def "Add"() { setup : expect : where: } def "Relax"() { setup : expect : where: }
-
Shay about 9 yearsAs i wrote, i tried it, and i need a cleanup once at the end of all the iterations.
-
th3morg almost 8 yearsIt is possible that you may need to @Unroll your method in order for it to cleanup after each iteration.
-
jaco0646 about 4 yearsThis is the correct answer, but note that it requires moving the test to its own class file; otherwise the
cleanupSpec
will wait for all tests to complete, potentially with polluted data.