Unit testing Grails domain classes with GORM without a database
Unit testing a Grails domain class asks whether its business rules behave correctly before a request reaches a real database. It is especially useful for validation, defaults, calculated fields, and state transitions in an order, subscription, or account. A fast specification provides clear feedback without shared test data, schema setup, or a connection pool.
GORM supplies persistence operations such as saving, deleting, finding, and counting records. Unit tests do not need to send SQL to exercise those operations. Grails’ GORM mock support intercepts them and maintains an in-memory representation of each domain class, allowing assertions against the domain API without a JDBC connection, database URL, or schema.
That distinction prevents a common misconception. A passing mocked test can show that a zero discount is rejected, yet it cannot prove that a real unique index handles simultaneous inserts, that a particular database casts a column correctly, or that a transaction rolls back under contention. These guarantees belong in integration tests using a disposable database.
This guide builds a small coupon domain and covers validation, querying, deletion, business calculations, and the limits of GORM mocking. It also connects domain testing to Australian pricing, privacy obligations, consumer guarantees, cyber security, and online gambling rules, keeping the examples fast, deterministic, and explicit about what they leave to the database.
Set up a database-free GORM test
Modern Grails applications normally run Spock specifications from src/test/groovy. Import grails.testing.gorm.MockGormSupport and implement it on the specification. Older Grails projects often provide unitTestMixin and mockDomain; retain the API used by that project instead of mixing versions.
Consider a coupon whose validity depends on a code and a discount rate:
class Coupon {
String code
BigDecimal discountRate
static constraints = {
code nullable: false, blank: false
discountRate nullable: false, min: 0.0, max: 1.0
}
}
The test then uses the mocked GORM operations as naturally as it would use persistent records:
import grails.testing.gorm.MockGormSupport
import spock.lang.Specification
class CouponSpec extends Specification implements MockGormSupport {
void "saves a valid coupon"() {
given:
Coupon coupon = new Coupon(code: "SAVE10", discountRate: 0.10)
when:
Coupon saved = coupon.save(failOnError: true)
then:
saved != null
Coupon.count() == 1
Coupon.findByCode("SAVE10") == coupon
}
}
The mocked domain is recreated for each test, so one specification cannot accidentally rely on records left by another. Keep assertions centred on observable behaviour, such as the number of stored objects or the result of a finder. Database-generated identifiers, sequences, and lifecycle callbacks are better verified in an integration test.
Test validation separately from persistence
Call validate() when the precise validation result matters. It populates the domain’s errors object without depending on how a record would later be persisted, making it suitable for testing blank values, ranges, nullable properties, and custom validators.
void "rejects a blank code and excessive rate"() {
given:
Coupon coupon = new Coupon(code: " ", discountRate: 1.20)
when:
boolean valid = coupon.validate()
then:
!valid
coupon.errors.getFieldError("code") != null
coupon.errors.getFieldError("discountRate") != null
}
These assertions describe the rule rather than the mechanism used to report it. They remain useful if a later Grails release changes the exception type or error-handling sequence. Testing validate() directly also avoids confusing a rejected value with a persistence failure caused by another condition.
A database-free test does not prove the existence of a physical unique index, a check constraint, or a foreign key. The mock may implement application-level validation differently from the selected database engine. Keep a schema-level test for those guarantees, especially where concurrent requests or imported data could bypass ordinary domain validation.
Exercise queries and lifecycle operations
Mocked GORM support is useful for common dynamic finders and straightforward persistence calls. A specification can therefore check that a saved object can be retrieved and removed without starting a database:
void "finds and removes a saved coupon"() {
given:
Coupon coupon = new Coupon(code: "SAVE10", discountRate: 0.10)
coupon.save(failOnError: true)
when:
Coupon found = Coupon.findByCode("SAVE10")
then:
found == coupon
when:
coupon.delete()
then:
Coupon.count() == 0
}
Keep the query under test simple in the mocked layer. Exact support for HQL, projections, locking, and complex criteria varies between Grails versions, and a mock does not reproduce the SQL generated by Hibernate. Unit tests should verify which record the domain intends to select; an integration test can confirm that the production dialect translates that selection correctly.
Lifecycle operations also have limits. A mocked save() or delete() does not fully reproduce flush timing, dirty checking, optimistic locking, transaction rollback, or audit behaviour. Test business state transitions explicitly, then cover the mechanics that require a real database in a separate suite.
Keep domain logic independent of ORM callbacks
GORM callbacks such as beforeInsert, beforeUpdate, and beforeDelete are not reliable substitutes for direct unit tests. A mocked operation may not execute every callback, and a callback containing important calculations can become difficult to exercise. Put significant business behaviour in an ordinary domain method or a service, then call that method from the persistence workflow and test it directly.
BigDecimal discountedTotal(BigDecimal subtotal) {
subtotal.multiply(BigDecimal.ONE.subtract(discountRate))
.setScale(2, RoundingMode.HALF_UP)
}
A unit test can verify the boundary values, rounding mode, and null handling without any persistence operation. Using BigDecimal avoids the representation errors that commonly appear when monetary calculations pass through double. If a callback must remain, ensure the integration suite demonstrates that it runs and produces the expected state.
Keep association testing similarly focused. Simple belongsTo and hasMany relationships can be represented in memory, but lazy loading, fetch strategies, cascade behaviour, and database ordering may differ. Test the service decisions involving those relationships, then verify the actual mapping through the integration layer.
Encode Australian market and legal assumptions
Australian consumer applications commonly calculate in Australian dollars and display GST-inclusive prices. Domain objects should identify their currency and amount rather than storing a dollar sign, while tests can pin invoice rounding and discount boundaries. The Australian Consumer Law also affects advertised prices, guarantees, refunds, and cancellation terms; automated tests can protect calculations, while legal wording and policy still require review.
Personal information introduces another distinct concern. The Privacy Act 1988 and the Australian Privacy Principles govern how organisations collect, use, disclose, store, and correct personal information. A test might ensure that consent metadata exists and that a retention date is calculated correctly, but it cannot establish that a collection notice is understandable or that every processing purpose complies with OAIC guidance.
Security tests also have an Australian context. ACSC Scamwatch guidance reflects the phishing and payment-redirection attempts regularly reported by households and small businesses. Domain tests can verify that a reset token expires, a one-time code cannot be reused, and a suspicious-account marker survives persistence. Test data and verification services should always be fake, with no live SMS, email, payment-card, or identity connections.
If an application serves online betting, legal requirements are not uniform across the country. State and territory codes and the Commonwealth’s Interactive Gambling Act 2001 can affect which promotions may be offered and how they may be communicated. For a domain that stores return-to-player information, the RTP explained checklist can help separate a published figure from its underlying calculation. Tests should pin rounding and permitted values, while legal review determines whether a state-specific offer can run.
Use mocks within a release workflow
Australian development teams often work across Sydney, Melbourne, and Brisbane, where clocks and working hours differ. A mocked suite that finishes in seconds is particularly valuable before a morning deployment window in the relevant city. Keep these specifications separate from integration tests, use fixed clocks where necessary, and avoid shared fixtures. A test that contacts a network service or a developer’s local database no longer provides the isolation expected of a unit test.
Retain a smaller integration suite that starts a disposable database for behaviour the mock cannot prove. It should cover migrations, generated SQL, physical uniqueness constraints, transaction semantics, and optimistic locking. Once the application is running, Spring Boot health checks can show whether the service and its dependencies are ready. A healthy endpoint confirms operational availability, not the correctness of every domain invariant.
Release gates should state exactly what must pass: mocked specifications green, integration tests green against the production database engine, security scans clean, and a rollback artefact available. Secrets belong in the deployment environment rather than test fixtures. If a test needs a live connection or external service, classify it as an integration test instead of hiding its cost and fragility behind the unit-test label.
Create a focused MockGormSupport specification for one validation rule or calculation that currently depends on a shared database. Run it with grails test-app, keep the database switched off, and confirm that the test explains the expected business outcome clearly.
Add an integration test only where the mock cannot represent the guarantee, such as a database-level unique constraint or transaction rollback. That boundary gives Australian teams fast local feedback while preserving release confidence for real customers and real data.