Skip to content

Grails: mocking domain objects in unit tests


We’re trying Grails, Rails-like web application framework for Java.
It’s fine, just that Groovy debugger support is, er, imperfect, even in the best Gruoovy IDE – IDEA.

And, if you want to unit test, you won’t have fancy domain class methods addTo* – like Customer.addToOrders().
They’re generated by Grails on startup.
In order to have addTo*(), inherit from GrailsUnitTestCase and call mockDomain(Customer) in setUp().

Oh, if you get "NullPointerException: Cannot invoke method containsKey() on null object", add super.setUp() to yout testcase’s setUp().

Having proper save() is more tricky. Implementation from mockDomain() works to some extent: it won’t save connected objects.
So, in order to get save() working, you have to do something like this:

    def savedCustomers = []

    void setUp() {
        super.setUp()
        Customer.metaClass.save = { saveCustomer(delegate) }
        mockDomain(Customer, savedCustomers)
    }

    private def saveCustomer(c) {
        savedCustomers.add(c)
        if (c.orders != null) {
            c.orders.each { x -> x.save() }
        }
    }

3 Comments

  1. Søren Berg Glasius wrote:

    When using Grails 1.2-M3 this is nolonger needed (as far as I can see)

    /Søren

    Posted on 04-Nov-09 at 10:47 | Permalink
  2. Great, thanks.

    I wonder — will save() work and what will it do.
    And will addTo*() assign both ends of connection.

    Anyway, will migrate when 1.2 is released and will know it all.

    Posted on 04-Nov-09 at 11:16 | Permalink
  3. Beaumont Muni wrote:

    Appreciate the Post … good post and has helped ..

    thanks …

    Posted on 01-Mar-11 at 19:00 | Permalink

Post a Comment

Your email is never published nor shared.