2

Given an extended example from the Grails documentation (http://grails.org/doc/latest/guide/async.html#asyncRequests):

import static grails.async.Promises.*

class myController {

    def myServiceWithLongRunningMethod

    def index() {
       tasks otherValue: {
           // do hard work
           myServiceWithLongRunningMethod.doSomething()
         }
    }
}

How do I create a Spock unit test for this?

import static grails.async.Promises.*
import org.grails.async.factory.*
import grails.async.*
import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(MyController)
class MyControllerSpec extends Specification {

    def mockMyServiceWithLongRunningMethod = Mock(MyServiceWithLongRunningMethod)

    def setup() {
        // not sure if I need this next line
        // Grails docs suggests making Promises synchronous for testing
        Promises.promiseFactory = new SynchronousPromiseFactory()
        controller.myServiceWithLongRunningMethod = mockMyServiceWithLongRunningMethod
    }

    def cleanup() {
    }

    void "index calls myServiceWithLongRunningMethod.doSomething()"() {
        when: 'index is called'
        controller.index()

        then: 'myServiceWithLongRunningMethod.doSomething() is called'
        1 * mockMyServiceWithLongRunningMethod.doSomething()
    }
}

I get the following error:

Failure:  index calls myServiceWithLongRunningMethod.doSomething()(MyControllerSpec)
|  groovy.lang.MissingPropertyException: No such property: tasks for class: MyLoadingController

I'm not sure what the tests should look like - it's clear that I need to do something to enable the test class to understand the tasks method provided by Promise.

Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
John
  • 10,837
  • 17
  • 78
  • 141
  • No @pherris, sorry, not yet unfortunately. It's gone on the back burner but I'm hoping to get a chance to look at it shortly. – John Apr 01 '15 at 15:16
  • Cool, I'd be interested in how it works out - I ended up using https://grails.org/plugin/executor because I was doing more GORM stuff on the asynchronous task. – pherris Apr 01 '15 at 15:19
  • On reflection, I think I'll look at making the test an integration one as perhaps the unit test mixing doesn't add the Promise methods. – John Apr 01 '15 at 15:40
  • 1
    for completeness' sake, the solutions offered within the following should help those who visit this page today: https://stackoverflow.com/questions/30596733/unit-testing-promise-task-in-grails – Jay Edwards Jan 19 '18 at 14:22

0 Answers0