11 December 2014

Tags: grails debugging

Method on class [] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

Note

java.lang.IllegalStateException: Method on class [com.willis.heimdall.Booking] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly. at com.willis.heimdall.BookingIntegSpec.test saving a booking to the db(BookingIntegSpec.groovy:24)

I recently had this error on one of my simple examples. A real facepalm moment when I look back in retrospect but ho hum, the fix is nice and easy.

Broken Code:

package com.willis.heimdall

import org.joda.time.DateTime
import spock.lang.Shared
import spock.lang.Specification

/**
 * Integration tests for the Booking model
 * @author Sion Williams
 */
class BookingIntegSpec extends Specification {
    @Shared def today = new DateTime()
    @Shared def todayPlusWeek = today.plusWeeks(1)

    def 'test saving a booking to the db'() {
        given: 'a new booking booking'
        def booking = new Booking(name: 'my booking',
                startTime: today.toDate(),
                endTime: todayPlusWeek.toDate())

        when: 'the booking is saved'
        booking.save()

        then: 'it can be successfully found in the database'
        booking.errors.errorCount == 0
        booking.id != null
        Booking.get(booking.id).name == 'my booking'
        Booking.get(booking.id).startTime == today.toDate()
        Booking.get(booking.id).endTime == todayPlusWeek.toDate()

    }
}

Fixed Code:

package com.willis.heimdall

import grails.test.mixin.TestFor
import org.joda.time.DateTime
import spock.lang.Shared
import spock.lang.Specification

/**
 * Integration tests for the Booking model
 * @author Sion Williams
 */
@TestFor(Booking)
class BookingIntegSpec extends Specification {
    @Shared def today = new DateTime()
    @Shared def todayPlusWeek = today.plusWeeks(1)

    def 'test saving a booking to the db'() {
        given: 'a new booking booking'
        def booking = new Booking(name: 'my booking',
                startTime: today.toDate(),
                endTime: todayPlusWeek.toDate())

        when: 'the booking is saved'
        booking.save()

        then: 'it can be successfully found in the database'
        booking.errors.errorCount == 0
        booking.id != null
        Booking.get(booking.id).name == 'my booking'
        Booking.get(booking.id).startTime == today.toDate()
        Booking.get(booking.id).endTime == todayPlusWeek.toDate()

    }
}

Note here that we have told Grails what we are testing with the @TestFor() annotation so that it can set up the relevant mocks and stubs in the background.


comments powered by Disqus