Spock测试:在“ where:”块完成后清洗

问题描述 投票:6回答:3

我有2种测试方法。

它们都执行where块的每一行,我需要清理添加和放松方法。

我已经尝试过cleanup block,void cleanup(),def cleanupSpec(),non suits。

如何在具有“ where:”块的特定方法之后显式运行清理?

def "Add"() {
   setup :
   expect : 
   where:
    }

def "Relax"() {
   setup :
   expect : 
   where:     
    }
groovy spock
3个回答
13
投票

您可以像下面这样在您的方法中包含清除块:

@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']
}

“ cleanup”块将在每个测试迭代中运行一次。


4
投票

如果使用@Unroll,则将为cleanup:块中的每个条目调用where:。要仅运行清除once,然后将代码移到def cleanupSpec()闭包内。

@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)
  }
}

0
投票

cleanupSpec()不可用,因为它是在all规格测试之后而不是最后一个“ where”项之后调用的。

如果您的规范将包含多个测试,则数据库将仍然被“一种测试材料的方法”中的材料所污染,直到该文件中的所有测试都将完成。

© www.soinside.com 2019 - 2024. All rights reserved.