【问题标题】:Spock testing : cleaning after "where:" block finishesSpock 测试:在“where:”块完成后进行清理
【发布时间】:2015-04-27 14:45:10
【问题描述】:

我有 2 种测试方法。

它们都执行 where 块的每一行,我需要清理 add 和 Relax 方法。

我试过 cleanup block 、 void cleanup() 、 def cleanupSpec() 、 non suits 。

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

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

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

【问题讨论】:

  • 有点不清楚。可以举个例子吗?
  • 没关系,我只是在 'add' 和 'relax' 之间添加了一个新方法,称为 'addClean' ,然后从那里重置所有内容。
  • 我的清理方法 -> def "添加清理 - 不是测试"() { 期望:!cache.clear() }
  • 我偶然发现了这个问题,并注意到这个问题有点不清楚,老实说,您在上面的评论中的解决方案也是如此。您是否可以改写问题以更清楚地说明您要问什么,用您的工作解决方案提供问题的答案并将其标记为正确,还是应该一起删除/关闭这个问题?

标签: groovy spock


【解决方案1】:

你可以像这样在你的方法中有一个清理块:

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

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

【讨论】:

  • 正如我所写,我试过了,我需要在所有迭代结束时清理一次。
  • 您可能需要 @Unroll 您的方法以便在每次迭代后对其进行清理。
【解决方案2】:

如果您使用@Unroll,那么cleanup: 将为where: 块中的每个条目调用。要只运行清理一次,然后将您的代码移动到 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)
  }
}

【讨论】:

  • 这是正确答案,但请注意,它需要将测试移动到自己的类文件中;否则,cleanupSpec 将等待 all 测试完成,可能带有污染的数据。
【解决方案3】:

cleanupSpec() 无法使用,因为它是在规范的所有测试之后调用的,而不是在最后一个“where”项之后调用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多