我正在为我的程序创建一个单元测试。我有一个void方法,它接受五个参数,然后将这些参数转换为一个闭包,并将其传递给另一个服务,转换成电子邮件并发送。我唯一关心的是这封电子邮件的正文,它存储在传递给此函数的一个参数中。是否可以在不改变程序设计的情况下验证此参数?
我考虑过使用Spock样式的模拟,但是我无法确定我是否可以在经过规范测试的类中实际模拟/存根方法,或者我是否只能模拟出依赖项。
Class myTestService
{
def outsideService
private void sendEmail (User source, String subj, String body, List to, List attachments){
outsideService.sendMail{
//blah blah
subject subj
html wrapWithDefault(body) //wrapWithDefault is a big styling document also in this function
//blah blah
}
}
int send(GrailsParameterMap params, HttpServletRequest request) {
//Parse out attachments from request and body/subject/addressee from params
//little bit of business logic to ensure that we can send emails in our system
sendEmail(source,
subject,
"$body <br /><br /> important extra information",
sendTo,
attachments)
//Send another email to the source as a receipt
sendEmail(source,
subject,
"$body extra junk $receiptBody",
source,
attachments)
}
}
我需要查看收据是否正确添加了receiptBody。鉴于我正在向outsideService发送一个闭包,很难从中删除变量,所以我有点亏。
编辑:为了回应下面的答案,我在我的测试中插入了spock样式模拟,但我认为我没有正确的语义,因为值存储为null。 void“#value contains#params.body”() { 给出: //def params, request, filling in all necessary values
def value
def mailServiceMock = Mock(MailService)
mailServiceMock.sendMail(*_) >> {closure ->
closure.delegate = new Expando(
multipart:{},
from: {},
subject: {},
html: {value = it}
bcc: {}
)
closure()
}
//inform service of mock
service.mailService = mailServiceMock
when:
service.send(params, request)
then:
println("value = $value")
1 * mailServiceMock.sendMail(*_) // this should fail, since this should be called twice, but one thing at a time.
value.contains(params.body)
}
值显示为null。有什么想法吗?
答案 0 :(得分:2)
您可以模拟您的服务。
这是一个非常简单的脚本,它扼杀outsideService
以将html
方法中收到的值存储在脚本var中。你应该去Spock / JUnit / YouNameIt来使这个整洁。
class MyTestService
{
def outsideService
private void sendEmail (source, String subj, String body, List to, List attachments){
outsideService.sendMail{
subject subj
html "<body>$body</body>"
}
}
}
myTest = new MyTestService()
def body
myTest.outsideService = [sendMail: { closure ->
closure.delegate = new Expando(
subject: { }, //don't care
html: { body = it }
)
closure()
}]
myTest.sendEmail(null, 'my subject', 'my email body', null, null)
assert '<body>my email body</body>' == body