Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock testing : cleaning after "where:" block finishes

Tags:

groovy

spock

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:     
    }
like image 442
Shay Avatar asked Apr 27 '15 14:04

Shay


2 Answers

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.

like image 62
th3morg Avatar answered Nov 24 '22 00:11

th3morg


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)
  }
}
like image 33
Mikael Olsson Avatar answered Nov 23 '22 23:11

Mikael Olsson