Dark theme | Light theme

August 19, 2013

Grails Goodness: Set Request Locale in Unit Tests

There is really no excuse to not write unit tests in Grails. The support for writing tests is excellent, also for testing code that has to deal with the locale set in a user's request. For example we could have a controller or taglib that needs to access the locale. In a unit test we can invoke the addPreferredLocale() method on the mocked request object and assign a locale. The code under test uses the custom locale we set via this method.

In the following controller we create a NumberFormat object based on the locale in the request.

package com.mrhaki.grails

import java.text.NumberFormat

class SampleController {

    def index() {
        final Float number = params.float('number')
        final NumberFormat formatter = NumberFormat.getInstance(request.locale)
        render formatter.format(number)


If we write a unit test we must use the method addPreferredLocale() to simulate the locale set in the request. In the following unit test (written with Spock) we use this method to invoke the index() action of the SampleController:

package com.mrhaki.grails

import grails.test.mixin.TestFor
import spock.lang.Specification
import spock.lang.Unroll

class SampleControllerSpec extends Specification {

    def "index must render formatted number for request locale #locale"() {
        given: 'Set parameter number with value 42.102'
        params.number = '42.102'

        and: 'Simulate locale in request'
        request.addPreferredLocale locale

        when: 'Invoke controller action'

        then: 'Check response equals expected result'
        response.text == result

        locale           || result
        Locale.US        || '42.102'
        new Locale('nl') || '42,102'
        Locale.UK        || '42.102'


Code written with Grails 2.2.4