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

Automatic continuous monitoring keeps continuous deployment pipelines flowing smoothly and efficiently. Try Instana APM to automatically monitor containers and microservices!

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++ }
    }

Automatic real-time observability is critical to getting the full benefit of CI/CD. Hear @DevOpsDon discuss how Franklin American Mortgage Company cut their new application deployment time from 6-12 months to 2 weeks with the help of Instana APM.

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 }}