Testing Grails controllers with MockCollaborators

Controllers are often easiest to understand as traffic directors. They receive HTTP parameters, coordinate application services, and choose an appropriate response such as a rendered view, JSON document, error status, or redirect. Testing those decisions in isolation gives developers fast feedback without starting the full Grails application, loading a database, or waiting for a server.

Testing Grails Controllers with MockCollaborators lets a specification control those surrounding dependencies directly. The result is a fast unit test that still explains how a controller behaves. This approach is particularly valuable for distributed teams in Sydney and Melbourne, where a small, dependable test suite can provide consistent feedback across different development environments.

Why isolated controller specs matter

A controller specification should concentrate on the controller’s own responsibilities: reading parameters, invoking collaborators, and producing the correct response. Business calculations, database queries, and external API calls belong behind collaborators that can be controlled by the test. This separation keeps each test focused on one clear behaviour and makes failures easier to diagnose.

Mocking is not a replacement for integration testing. A unit spec can prove that a controller calls AccountService.register() once and redirects to the welcome page, but it cannot prove that the service stores a valid record or that a database migration works. The two layers complement each other: isolated specs protect controller design, while integration tests verify the assembled Grails application.

Setting up a focused controller spec

Start with a small controller whose dependencies are obvious. This registration action accepts a command object, validates it, delegates persistence to a service, and redirects when successful:

class AccountController {
    AccountService accountService

    def register() {
        def command = new RegistrationCommand()
        command.properties = params

        if (!command.validate()) {
            respond command, errors: true, status: 422
            return
        }

        accountService.register(command)
        redirect(uri: '/accounts/welcome')
    }
}

In a Grails project that provides the MockCollaborators trait, a Spock specification can create the controller and replace its service with a mock:

import grails.test.MockCollaborators

class AccountControllerSpec extends Specification implements MockCollaborators {
    AccountController controller
    AccountService accountService

    def setup() {
        controller = new AccountController()
        accountService = mock(AccountService)
        controller.accountService = accountService
    }
}

The helper names available to a specification can vary between Grails and Spock versions. If mock() is not exposed by the project’s testing support, use the mock or stub helper supplied by that version and apply the same principles. The important part is that the collaborator is injected explicitly rather than obtained from a real application context.

Defining collaborator behavior

A collaborator mock is a programmable stand-in for a service, repository, publisher, or client. It can return a value, throw an exception, or record an argument for later inspection. This allows a controller spec to describe the service contract from the controller’s point of view without implementing the service’s internal logic.

For example, a service might need to return an account identifier after registration. That return value can be stubbed without creating an account in the database:

given:
accountService.register(_) >> { command ->
    command.accountId = 42
}

when:
def result = controller.register()

then:
result.accountId == 42

Interaction rules are useful when the call itself is the behaviour under examination. A declaration such as 1 * accountService.register(_) requires exactly one registration call with any suitable argument. A different count can express that a service must not be called, while a closure can inspect a command object before returning. Avoid mocking every class in the path: value objects, simple data holders, and collaborators with stable behaviour often work better as real instances.

Simulating requests and inspecting responses

Grails unit tests can use MockHttpServletRequest and MockHttpServletResponse to represent the HTTP exchange. Populate the request method and parameters, attach both objects to the controller, and invoke the action directly. This avoids a running server while still exercising the controller’s parameter binding and response handling.

A complete registration example might look like this:

def "a valid registration redirects to the welcome page"() {
    given:
    def request = new MockHttpServletRequest()
    def response = new MockHttpServletResponse()
    request.method = 'POST'
    request.addParameter('email', 'sam@example.com')

    controller.request = request
    controller.response = response
    controller.params = request.parameterMap

    when:
    controller.register()

    then:
    response.redirectedUrl == '/accounts/welcome'
    1 * accountService.register(_)
}

Direct action invocation does not automatically reproduce every part of the Grails request lifecycle. Filters, interceptors, URL mappings, and some framework callbacks may require separate integration coverage. Keep those checks at the application level, where the real infrastructure is available.

Checking outcomes without brittle assertions

Assertions should describe observable behaviour rather than incidental implementation details. For a redirect, inspect the redirected URL and required call count. For rendered text or JSON, inspect the response body and content type. For a model-driven response, check the values a caller needs. Exact wording may change during a redesign, whereas a status code, redirect destination, or submitted field usually represents a stable requirement.

State-based and interaction-based assertions serve different purposes. State-based checks confirm the returned result, while interaction-based checks confirm that the controller used its collaborator correctly. A useful specification often includes both when both matter. It also names the scenario clearly, such as “an inactive account cannot be activated”, so a failed build identifies the broken rule without requiring the reader to decode method names and assertion ordering.

Protecting validation and business rules

Command objects and domain classes need their own validation coverage. A controller can correctly check command.validate(), but that check is only meaningful if the command’s constraints behave as expected. mockForConstraintsTests can help simulate constraint behaviour, including uniqueness checks that would otherwise require database access. Test an invalid value, a valid value, and any boundary condition that affects whether the collaborator should be called.

Security deserves similar attention. A redirect to /admin does not prove that an ordinary user was denied access, and invoking an action directly may bypass checks performed by filters or interceptors. The Grails security basics guide provides useful background on authentication and authorisation controls that should be tested at the appropriate layer.

For Australian applications, legal requirements can influence the controller contract. The Privacy Act 1988 may apply to personal information held by an organisation, while the Spam Act 2003 governs many commercial electronic messages. A registration controller should therefore avoid exposing raw personal data in error messages or logs. Those expectations are easier to protect when security-related outcomes are explicit in the test suite.

Building a dependable controller testing habit

Keep the suite fast by following a consistent sequence: arrange the request, define collaborator behaviour, invoke the action, and assert the response. Give each example one purpose, reset collaborators between examples, and prefer realistic values over placeholders that conceal formatting errors. CI can then run the same suite on every change, whether a developer is working from Brisbane, Perth, or another Australian city.

Local market context can also shape useful scenarios. Community esports is a recognisable part of the Australian online market, and esports community coverage illustrates the kinds of fixture, membership, and notification journeys that community platforms support. An Australian audience may check competition updates on a phone while having a coffee or travelling to work, making mobile-friendly responses and dependable redirects especially relevant.

Start with the next Grails controller change in your project: write one focused specification, replace its slowest dependency with a controlled mock, and make the resulting suite a required check before code reaches the shared branch. This creates fast, readable feedback without losing sight of the behaviour real users depend on.