Grails Unit Testing and a little fun with @Before

So, we’ve been using Grails at gibbon’s five for a while now and stumbled into different problems with our unit tests. One of the weirdest ones were occasionally failing tests on our Jenkins that never failed locally. So we digged into this a little and came up with a simple explanation, that I’d like to share with you.

Let’s assume we have a controller and want to test it. First thing you’d probably do is go to the Grails Guide, Chapter 10: Unit Testing Controllers and start with something like this:

import grails.test.mixin.TestFor

@TestFor(SimpleController)
class SimpleControllerTests {
    void testSomething() {
    }
}

Now, if you have multiple tests which need some variable set inside the (controller.)request and you have a little knowledge of JUnit, you’d probably come up with something like this:

import grails.test.mixin.TestFor
import org.junit.Before

@TestFor(SimpleController)
class SimpleControllerTests {
    @Before
    void initialize() {
        request.variable = "foobar"
    }
    void testSomething() {
        // some code here needs the request.variable
    }
    void testSomethingElse() {
        // some code here needs the request.variable
    }
}

This is bad.

Continue reading “Grails Unit Testing and a little fun with @Before” »