2016-02-19 47 views
2

我试图验证,在一类这个常规闭合称为CUTService有正确的价值观:试图验证的Groovy闭包在一个单元测试

mailService.sendMail { 
    to '[email protected]' 
    from '[email protected]' 
    subject 'Stuff' 
    body 'More stuff' 
} 

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

1 * mailService.sendMail({ Closure c -> c.to == '[email protected]'}) 

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

我已经看了Is there any way to do mock argument capturing in Spock,并试图此:

1 * mailService.sendMail({closure -> captured = closure }) 
assertEquals '[email protected]', captured.to 

主要生产:

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

我也试过这样:

1 * mailService.sendMail({captured instanceof Closure }) 
assertEquals '[email protected]', captured.to 

主要生产:

Too few invocations for: 
1 * mailService.sendMail({captured instanceof Closure }) (0 invocations) 

... 

Unmatched invocations (ordered by similarity): 
1 * mailService.sendMail([email protected]) 

什么我需要做的就是这个工作?

回答

3

当你写:

mailService.sendMail { 
    to '[email protected]' 
    from '[email protected]' 
    subject 'Stuff' 
    body 'More stuff' 
} 

事实上,您正在执行的方法sendMail,具有封闭℃。 sendMail创建一个委托,并用这个委托调用你的闭包。你封在现实中执行如下:

delegate.to('[email protected]') 
delegate.from('[email protected]') 
delegate.subject('Stuff') 
delegate.body('More stuff') 

为了测试这种封,你应该创建一个模拟,配置封授人以这种模拟,调用关闭,并验证模拟的期望。

由于这个任务是不是真的微不足道,这是更好地重用邮件插件,并创建了自己的邮件建设者:

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("[email protected]") 
    1 * messageBuilder.from("[email protected]") 
+0

您的意思是'1 * mailService.sendMail'? Spec中没有sendMail。尽管如此,采用这种方法即使在CUT出错的情况下也能通过测试。 –

+0

我只能向您展示您可以编写的测试类型以及它的工作原理,但是如果没有更多的上下文,您的课程等,我无法编写一份工作测试! ;-) –

+0

它适用于您的编辑。谢谢! –