Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to mock domain specific closures in Spock
    text
    copied!<p>I'd like to test a Grails controller that is sending out emails using the grails Email plugin. I'm at a loss exactly how to mock the <code>sendMail</code> closure in order for interactions to work. Here's my latest version of the test code:</p> <pre><code>def 'controller should send a multipart email'() { given: 'a mocked mailService' controller.mailService = Mock(grails.plugin.mail.MailService) controller.mailService.sendMail(*_) &gt;&gt; Mock(org.springframework.mail.MailMessage) when: controller.sendNow() then: 1* _.multipart(true) } </code></pre> <p>The controller code looks something like what you'd expect, e.g.:</p> <pre><code>def mailService def sendNow() { mailService.sendMail { multipart true to 'example@example.org' from 'me@here.com' subject 'a subject' body 'a body' } } </code></pre> <p>If I run this test, I get 0 invocations of my <code>multipart</code> interaction instead of 1. The second line of the <code>given:</code> block seems suspicious to me, but if I try to mock a <code>Closure</code> instead of <code>org.springframework.mail.MailMessage</code> my test crashes. I should also mention that the controller itself works as expected (it couldn't wait for me to figure out the unit tests first).</p> <h2>Edited</h2> <p>Aha, looking at the code with a fresh mind a few hours later, I can see why the above code does not work; in order for me to catch <code>multipart</code> and other DSL calls, I would have to mock the closure itself, not the sendMail method (and I can't do that since the closure is defined inside the controller itself). What I probably can do is check the <em>arguments</em> to the <code>sendMail</code> method to see everything necessary was passed into it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload