Grails Build-test-data 1.1 Released With New buildLazy Functionality

| Comments

Version 1.1 of the build-test-data plugin has just been released.

It adds a new buildLazy method that will only create a new object graph if it can’t find an existing object that matches the build criteria specified.


    def a = new Author(firstName: "Ray", lastName: "Bradbury")
    assert 1 == Author.count()

    // Author table already has Ray Bradbury in it, finds existing record
    def bradbury = Author.buildLazy(lastName: "Bradbury")  
    assert 1 == Author.count()
    assert bradbury.firstName == "Ray"

    def newAuthor = Author.buildLazy(lastName: "Moore")
    assert 2 == Author.count() // creates a new record, no existing "Moore" author previously

I find this particularly useful for building testing data in the grails console. It allows me to do some quick setup of new objects and then concentrate on creating the code that I actually want to try out. Without buildLazy, I was always commenting out my creation code so that multiple executions of the test script didn’t create multiple copies of the same data (and potentially hit unique constraints issues that I had to screw around with).

Now, I no longer need to worry about commenting out the creation code after running it the first time.


def u = User.buildLazy(ssn: "123-456-7890") // User.ssn has unique constraint

Before buildLazy I’d need to comment out the user creation and replace it with a user.findBySsn. Now buildLazy does the creation and later finding for me. I can concentrate on making foo/bar/baz do what I want them to (the reason I opened the console in the first place).