尝试在单元测试中验证Groovy闭包

时间:2016-02-19 15:35:39

标签: unit-testing groovy spock

我正在尝试验证名为CUTService的类中的这个groovy闭包是否具有正确的值:

<a>

我查看了https://github.com/craigatk/spock-mock-cheatsheet/raw/master/spock-mock-cheatsheet.pdf,但他的语法产生错误:

mailService.sendMail {
    to 'hey@example.com'
    from 'hey@example.com'
    subject 'Stuff'
    body 'More stuff'
}

我看了Is there any way to do mock argument capturing in Spock并尝试了这个:

1 * mailService.sendMail({ Closure c -> c.to == 'hey@example.com'})

groovy.lang.MissingPropertyException: No such property: to for class: com...CUTService

产生:

1 * mailService.sendMail({closure -> captured = closure })
assertEquals 'hey@example.com', captured.to

我也试过这个:

groovy.lang.MissingPropertyException: No such property: to for class: com...CUTService

产生:

1 * mailService.sendMail({captured instanceof Closure })
assertEquals 'hey@example.com', captured.to

我需要做些什么来实现这个目标?

1 个答案:

答案 0 :(得分:5)

当你写:

mailService.sendMail {
    to 'hey@example.com'
    from 'hey@example.com'
    subject 'Stuff'
    body 'More stuff'
}

实际上,您正在使用闭包c执行方法sendMail。 sendMail创建一个委托,并使用此委托调用您的闭包。你的关闭实际上是执行:

delegate.to('hey@example.com')
delegate.from('hey@example.com')
delegate.subject('Stuff')
delegate.body('More stuff')

要测试此闭包,您应该创建一个mock,将闭包的委托配置到此mock,调用闭包,并验证模拟期望。

由于这项任务并不是真的很重要,最好重复使用邮件插件并创建自己的邮件构建器:

given:
  def messageBuilder = Mock(MailMessageBuilder)

when:
   // calling a service

then: 
    1 * sendMail(_) >> { Closure callable ->
      callable.delegate = messageBuilder
      callable.resolveStrategy = Closure.DELEGATE_FIRST
      callable.call(messageBuilder)
   }
   1 * messageBuilder.to("hey@example.com")
   1 * messageBuilder.from("hey@example.com")