Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

build-test-data plugin: How to Generate IDs for Domain Entities in a Batch [Code Snippet]

DZone's Guide to

build-test-data plugin: How to Generate IDs for Domain Entities in a Batch [Code Snippet]

Adding in this expression in your Grails projects automates the creation of an ID for each created entity, saving a lot of time when testing.

· DevOps Zone ·
Free Resource

Easily enforce open source policies in real time and reduce MTTRs from six weeks to six seconds with the Sonatype Nexus Platform. See for yourself - Free Vulnerability Scanner. 

I have faced an issue in Grails projects: domain entities have an assigned id, so in tests, I have to manually set up an id for every created entity:

new Entity(id: id_value, ...).save() 

It is very verbose and creates an additional task to create and maintain id variables. In addition, there is a build-test-data plugin in our tests, so I was wondering if it is possible to get assistance from this plugin to generate IDs, and I found a solution: you have to add in TestDataConfig.groovy such expression:

testDataConfig {
    sampleData {
        ...
        Holders.grailsApplication.domainClasses.each { domainClass ->
            if (domainClass.fullName.startsWith('domain.package.to.get.ids')) {
                this."${domainClass.fullName}" {
                    long i = 1
                    this.id = { -> i++ }
                }
            }
        }
    }
}

The expression will generate next code for all domains in the package domain.package.to.get.ids:

'domain.package.to.get.ids.SomeEntity' {
        long i = 1
        this.id = { -> i++ }
    }

Automate open source governance at scale across the entire software supply chain with the Nexus Platform. Learn more.

Topics:
devops ,automated testing ,test automation ,grails ,groovy ,plugin ,tutorial ,code snippet

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}