Integration testing Grails services with data tables
A Grails service often sits at the centre of an application’s business rules. It may validate a booking, calculate a delivery charge, update several domain objects, or call another component before returning a result. Unit tests can check individual branches quickly, but integration tests reveal whether the service behaves correctly with Grails dependency injection, persistence, transactions and real validation rules.
Spock’s data tables are particularly useful for this work. A single specification can describe many meaningful business scenarios in a compact form, while Grails boots enough of the application to exercise the service in a realistic environment. The result is a test suite that is readable for Java developers, approachable for Groovy learners and practical for teams maintaining applications in Australian production environments.
Choose the right integration boundary
A service test should use the smallest realistic boundary that proves the behaviour. If the method only transforms a value, a unit specification may be sufficient. If it queries a domain class, relies on injected configuration, publishes an event or participates in a transaction, an integration specification is usually the better choice.
In a modern Grails application, an integration test commonly lives under src/integration-test/groovy. The exact annotations depend on the Grails and Spock versions in use, but the purpose is consistent: start the application context and inject the service as Grails would during normal execution.
package example
import grails.testing.mixin.integration.Integration
import grails.gorm.transactions.Rollback
import spock.lang.Specification
import spock.lang.Unroll
@Integration
@Rollback
class DeliveryFeeServiceSpec extends Specification {
DeliveryFeeService deliveryFeeService
@Unroll
def "calculates a delivery fee for #suburb and #weight kilograms"(...) {
expect:
deliveryFeeService.calculate(suburb, weight) == expectedFee
where:
suburb | weight | expectedFee
'Richmond' | 1.0 | 8.50
'Parramatta' | 4.5 | 12.00
'Fremantle' | 8.0 | 18.00
}
}
@Rollback is valuable when a test writes to a database. Each feature method can run inside a transaction that is rolled back after execution, leaving the test database ready for the next row or feature. This is generally safer than manually deleting every object, although tests should still avoid depending on records created by another test.
Keep external systems outside this boundary unless the integration itself is what you need to verify. A payment gateway, SMS provider or cloud storage service should normally be replaced with a stub or mock. The service can still use the real Grails configuration and persistence layer while the test remains deterministic and fast enough for a build pipeline.
Model scenarios as business data
A data table works best when each column represents a business input or an expected outcome. Avoid filling the table with internal implementation details such as method call counts, repository names or private flags. Those details make a test harder to understand and cause unnecessary changes when the service is refactored.
Suppose a service applies a surcharge based on a customer’s membership and the parcel’s weight. The table can express the policy directly:
@Unroll
def "applies #membership membership pricing to a #weight kg parcel"(...) {
given:
def customer = new Customer(membership: membership).save(failOnError: true)
when:
BigDecimal amount = deliveryFeeService.quote(customer.id, weight)
then:
amount == expected
where:
membership | weight | expected
'STANDARD' | 1.0 | 8.50
'STANDARD' | 6.0 | 15.00
'PREMIUM' | 1.0 | 0.00
'PREMIUM' | 6.0 | 7.50
}
The @Unroll annotation creates a separate, descriptive result for every row. When a build fails, the report can identify the exact combination of membership and weight rather than showing an opaque failure from one large parameterised test.
Use explicit values for boundaries and invalid inputs. Include zero, the smallest accepted value, the largest accepted value, and values just outside the permitted range. For money, use BigDecimal rather than binary floating-point values. A table containing 8.50 and 15.00 communicates the expected financial result more reliably than calculations based on double.
Australian applications often need rules involving suburb, postcode, state and time zone. A delivery table might include 2000 for central Sydney, 3000 for Melbourne and 6000 for Perth, while a booking table may distinguish Australian Eastern Standard Time from daylight-saving time. Keep these cases in the data table so the specification documents the rule rather than hiding it in setup methods.
Prepare persistent fixtures deliberately
Integration testing becomes unreliable when fixture creation is scattered across setup(), shared mutable fields and implicit database state. Prefer creating the records required by a feature method, then pass their identifiers into the service. This makes each data-table iteration independent and makes failures easier to reproduce.
A helper method can remove repetitive construction without hiding the important scenario:
private Customer createCustomer(String membership, boolean verified = true) {
new Customer(
membership: membership,
email: "${membership.toLowerCase()}@example.test",
verified: verified
).save(failOnError: true)
}
The test should still make its key assumptions visible:
where:
membership | verified | expectedException
'STANDARD' | true | null
'PREMIUM' | true | null
'PREMIUM' | false | CustomerNotVerifiedException
When a service reads a domain object more than once, call flush() after saving if the test needs database-generated values or wants to expose persistence constraints immediately. save(failOnError: true, flush: true) can be appropriate for a small fixture. It should not become a default everywhere, because unnecessary flushes slow a larger suite.
Be cautious with lazy associations and session boundaries. A test may pass because an object remains attached to the Hibernate session, while production code receives a detached object or runs after a transaction has ended. Exercise the same service method and transaction boundary used by the application. If the service is expected to reject missing records, include a null or nonexistent identifier as a dedicated table row and assert the documented exception.
For applications handling Australian customer information, fixture data should be synthetic. Do not place real names, Medicare details, payment data or identifiable addresses in source control. The Privacy Act 1988 and the Australian Privacy Principles make careless handling of personal information a serious operational risk, even in a test repository. Project documentation should also explain how test data and analytics are handled; the site’s privacy policy provides a useful example of this kind of transparency.
Test validation and failure paths
A service specification should verify more than the happy-path return value. Data tables are ideal for validation because they can cover several invalid combinations without duplicating the entire feature method.
@Unroll
def "rejects an order with quantity #quantity and stock #stock"(...) {
given:
def product = new Product(stock: stock).save(failOnError: true)
def command = new OrderCommand(productId: product.id, quantity: quantity)
when:
orderService.place(command)
then:
def error = thrown(OrderValidationException)
error.code == expectedCode
where:
quantity | stock | expectedCode
0 | 10 | 'quantity.invalid'
-2 | 10 | 'quantity.invalid'
11 | 10 | 'stock.insufficient'
}
When several exceptions are possible, assert the public error contract rather than a framework-specific message. Error messages can change with localisation or validation library upgrades. A stable error code, response type or domain state usually gives the test a stronger purpose.
For commands that modify multiple records, assert the complete outcome. If placing an order should create an order, reduce inventory and record an audit event, check each effect. A data table can include a flag such as shouldCreateAuditEntry, but avoid turning one feature into an enormous matrix. Split unrelated policies into separate specifications when a table becomes difficult to scan.
Use mocks for collaborators whose behaviour is outside the service’s responsibility:
def "records an audit event after a successful refund"() {
given:
def auditPublisher = Mock(AuditPublisher)
refundService.auditPublisher = auditPublisher
def refund = new Refund(amount: 25.00G).save(failOnError: true)
when:
refundService.process(refund.id)
then:
1 * auditPublisher.publish({
it.type == 'REFUND_PROCESSED' &&
it.amount == 25.00G
})
}
The real database can verify persistence while the mock confirms that the service sends the right message. This balance avoids connecting a test suite to a live queue or external vendor.
Account for dates, money and local rules
Dates are a common source of false confidence. A service that uses LocalDateTime.now() may pass in Melbourne and fail in Perth, or behave differently when daylight saving begins in New South Wales and Victoria. Inject a clock or pass the current date into the service so every data-table row uses a known value.
@Unroll
def "applies the correct booking status on #date"(...) {
given:
bookingService.clock = Clock.fixed(
date.atStartOfDay(ZoneId.of('Australia/Sydney')).toInstant(),
ZoneId.of('Australia/Sydney')
)
expect:
bookingService.statusFor(date) == expectedStatus
where:
date | expectedStatus
LocalDate.of(2025, 6, 1) | 'OPEN'
LocalDate.of(2025, 12, 25) | 'CLOSED'
}
Use the time zone that the business rule actually specifies. Australia/Sydney, Australia/Melbourne, Australia/Brisbane, Australia/Adelaide, Australia/Darwin and Australia/Perth do not all have the same daylight-saving behaviour. A national application should make that difference visible in its test cases instead of relying on the developer’s laptop settings.
Currency rules deserve the same care. Assert rounded BigDecimal values using the required scale and rounding mode. Include GST when the service is responsible for it, and distinguish an amount that includes GST from one that excludes it. Australian invoices, subscriptions and marketplace charges often have different treatments, so the table should name columns clearly, such as netAmount, gstAmount and grossAmount.
Test data can also reflect local operational realities: public holidays, postcode-based shipping zones, regional delivery cut-offs and scheduled jobs running on AEST or AEDT. This makes the integration suite useful to teams serving customers in Sydney, Melbourne, Brisbane and remote areas rather than treating all dates and locations as interchangeable.
Run the suite reliably in development and CI
A test that passes in IntelliJ but fails in CI often depends on an accidental database, environment variable or system locale. Configure a dedicated test environment and use the same database engine in CI that production uses where practical. H2 can be quick, but SQL behaviour, constraints and date handling may differ from PostgreSQL or another production database.
Run data-table specifications from the command line as part of the normal Grails workflow:
./gradlew integrationTest
For a focused run, use the Gradle test filter supported by the project:
./gradlew integrationTest \
--tests example.DeliveryFeeServiceSpec
Keep table rows deterministic and avoid random values unless the random seed is recorded. Do not depend on execution order. If a feature needs a reference record, create it in the feature or in a narrowly scoped fixture method. A clean test database should be an assumption, not a hidden dependency.
Australian teams may run builds across offices in Brisbane, Adelaide or Perth, with developers using different locale and time-zone settings. Set locale and time zone explicitly in the test process when the application depends on them. If the application is deployed to AWS or another cloud region outside Australia, test the business time zone independently from the server’s physical location.
Finally, publish readable reports and retain the failing data row in CI output. A failed parameterised test should tell the team which postcode, membership level, date or amount caused the problem. The Grails tutorials offer a practical starting point for checking version-specific testing conventions before adapting these patterns to an existing application.
Use these techniques to turn service rules into executable examples: define a realistic integration boundary, create isolated fixtures, encode edge cases in Spock tables and control time, money and database behaviour explicitly. Add one focused data-driven specification to your Grails project, run it locally and then include it in the CI build so every change is checked against the business rules that matter. For fixture design that uses cultural or travel-related examples, consult this guide to respectful temple photography and keep demonstration data considerate as well as technically useful.