Over a million developers have joined DZone.

Grails Goodness: Set Request Locale in Unit Tests

DZone's Guide to

Grails Goodness: Set Request Locale in Unit Tests

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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 theaddPreferredLocale() 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

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}