Spock, Java and Maven

Few months ago I’ve came across Groovy – powerful language for JVM platform which combines the power of Java with abilities typical for scripting languages (dynamic typing, metaprogramming). Together with Groovy I’ve discovered spock framework (https://code.google.com/p/spock/) – specification framework for Groovy (of course you can test Java classes too!). But spock is not only test/specification framework – it also contains powerful mocking tools. Even though spock is dedicated for Groovy there is no problem with using it for Java classes tests. In this post I’m going to describe how to configure Maven project to build and run spock specifications together with traditional JUnit tests. Firstly, we need to prepare pom.xml and add necessary dependencies and plugins. Two obligatory libraries are: <dependency> <groupid>org.spockframework</groupId> <artifactid>spock-core</artifactId> <version>0.7-groovy-2.0</version> <scope>test</scope></dependency><dependency> <groupid>org.codehaus.groovy</groupId> <artifactid>groovy-all</artifactId> <version>${groovy.version}</version> <scope>test</scope></dependency> Where groovy.version is property defined in pom.xml for more convenient use and easy version change, just like this: <properties> <gmaven-plugin.version>1.4</gmaven-plugin.version> <groovy.version>2.1.5</groovy.version></properties> I’ve added property for gmaven-plugin version for the same reason ;) Besides these two dependencies, we can use few additional ones providing extra functionality: cglib – for class mocking objenesis – enables mocking classes without default constructor To add them to the project put these lines in <dependencies> section of pom.xml: <dependency> <groupid>cglib</groupId> <artifactid>cglib-nodep</artifactId> <version>3.0</version> <scope>test</scope></dependency><dependency> <groupid>org.objenesis</groupId> <artifactid>objenesis</artifactId> <version>1.3</version> <scope>test</scope></dependency> And that’s all for dependencies section. Now we will focus on plugins necessary to compile Groovy classes. We need to add gmaven-plugin with gmaven-runtime-2.0 dependency in plugins section: <plugin> <groupid>org.codehaus.gmaven</groupId> <artifactid>gmaven-plugin</artifactId> <version>${gmaven-plugin.version}</version> <configuration> <providerselection>2.0</providerSelection> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupid>org.codehaus.gmaven.runtime</groupId> <artifactid>gmaven-runtime-2.0</artifactId> <version>${gmaven-plugin.version}</version> <exclusions> <exclusion> <groupid>org.codehaus.groovy</groupId> <artifactid>groovy-all</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupid>org.codehaus.groovy</groupId> <artifactid>groovy-all</artifactId> <version>${groovy.version}</version> </dependency> </dependencies></plugin> With these configuration we can use spock and write our first specifications. But there is one issue: default settings for maven-surefire plugin demand that test classes must end with “..Test” postfix, which is ok when we want to use such naming scheme for our spock tests. But if we want to name them like CommentSpec.groovy or whatever with “..Spec” ending (what in my opinion is much more readable) we need to make little change in surefire plugin configuration: <plugin> <groupid>org.apache.maven.plugins</groupId> <artifactid>maven-surefire-plugin</artifactId> <version>2.15</version> <configuration> <includes> <include>**/*Test.java</include> <include>**/*Spec.java</include> </includes> </configuration></plugin> As you can see there is a little trick ;) We add include directive for standard Java JUnit test ending with “..Test” postfix, but there is also an entry for spock test ending with “..Spec”. And there is a trick: we must write “**/*Spec.java”, not “**/*Spec.groovy”, otherwise Maven will not run spock tests (which is strange and I’ve spent some time to figure out why Maven can’t run my specs).Little update: instead of “*.java” postfix for both types of tests we can write “*.class” what is in my opinion more readable and clean: <include>**/*Test.class</include><include>**/*Spec.class</include> (thanks to Tomek Pęksa for pointing this out!) With such configuration, we can write either traditional JUnit test and put them in src/test/java directory or groovy spock specifications and place them in src/test/groovy. And both will work together just fine :) In one of my next posts I’ll write something about using spock and its mocking abilities in practice, so stay in tune.
Few months ago I’ve came across Groovy – powerful language for JVM platform which combines the power of Java with abilities typical for scripting languages (dynamic typing, metaprogramming).
Together with Groovy I’ve discovered spock framework (https://code.google.com/p/spock/) – specification framework for Groovy (of course you can test Java classes too!). But spock is not only test/specification framework – it also contains powerful mocking tools.
Even though spock is dedicated for Groovy there is no problem with using it for Java classes tests. In this post I’m going to describe how to configure Maven project to build and run spock specifications together with traditional JUnit tests.
Firstly, we need to prepare pom.xml and add necessary dependencies and plugins.
Two obligatory libraries are:
<dependency>
    <groupid>org.spockframework</groupId>
    <artifactid>spock-core</artifactId>
    <version>0.7-groovy-2.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupid>org.codehaus.groovy</groupId>
    <artifactid>groovy-all</artifactId>
    <version>${groovy.version}</version>
    <scope>test</scope>
</dependency>

Where groovy.version is property defined in pom.xml for more convenient use and easy version change, just like this:

<properties>
    <gmaven-plugin.version>1.4</gmaven-plugin.version>
    <groovy.version>2.1.5</groovy.version>
</properties>

 

I’ve added property for gmaven-plugin version for the same reason ;)
Besides these two dependencies, we can use few additional ones providing extra functionality:

 

  • cglib – for class mocking
  • objenesis – enables mocking classes without default constructor

 

To add them to the project put these lines in section of pom.xml:
<dependency>
    <groupid>cglib</groupId>
    <artifactid>cglib-nodep</artifactId>
    <version>3.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupid>org.objenesis</groupId>
    <artifactid>objenesis</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
And that’s all for dependencies section. Now we will focus on plugins necessary to compile Groovy classes. We need to add gmaven-plugin with gmaven-runtime-2.0 dependency in plugins section:
<plugin>
    <groupid>org.codehaus.gmaven</groupId>
    <artifactid>gmaven-plugin</artifactId>
    <version>${gmaven-plugin.version}</version>
    <configuration>
        <providerselection>2.0</providerSelection>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
                <goal>testCompile</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupid>org.codehaus.gmaven.runtime</groupId>
            <artifactid>gmaven-runtime-2.0</artifactId>
            <version>${gmaven-plugin.version}</version>
            <exclusions>
                <exclusion>
                    <groupid>org.codehaus.groovy</groupId>
                    <artifactid>groovy-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupid>org.codehaus.groovy</groupId>
            <artifactid>groovy-all</artifactId>
            <version>${groovy.version}</version>
        </dependency>
    </dependencies>
</plugin>
With these configuration we can use spock and write our first specifications. But there is one issue: default settings for maven-surefire plugin demand that test classes must end with “..Test” postfix, which is ok when we want to use such naming scheme for our spock tests. But if we want to name them like CommentSpec.groovy or whatever with “..Spec” ending (what in my opinion is much more readable) we need to make little change in surefire plugin configuration:
<plugin>
    <groupid>org.apache.maven.plugins
    </groupId>
    <artifactid>maven-surefire-plugin
    </artifactId>
    <version>2.15</version>
    <configuration>
        <includes>
            <include>**/*Test.java</include>
            <include>**/*Spec.java</include>
        </includes>
    </configuration>
</plugin>
As you can see there is a little trick ;) We add include directive for standard Java JUnit test ending with “..Test” postfix, but there is also an entry for spock test ending with “..Spec”. And there is a trick: we must write “**/*Spec.java”, not “**/*Spec.groovy”, otherwise Maven will not run spock tests (which is strange and I’ve spent some time to figure out why Maven can’t run my specs). Little update: instead of “*.java” postfix for both types of tests we can write “*.class” what is in my opinion more readable and clean:
<include>**/*Test.class</include>
<include>**/*Spec.class</include>

(thanks to Tomek Pęksa for pointing this out!)

With such configuration, we can write either traditional JUnit test and put them in src/test/java directory or groovy spock specifications and place them in src/test/groovy. And both will work together just fine :) In one of my next posts I’ll write something about using spock and its mocking abilities in practice, so stay in tune.
You May Also Like

EhCache config with BeanUtils

BeanUtils allows you to set Bean properties.If you have configuration stored in a Map it's tempting to use BeanUtils to automagically setup EhCache configuration.Sadly this class has mixed types in setters and getter and thus BeanUtils that use Introsp...

Grails session timeout without XML

This article shows clean, non hacky way of configuring featureful event listeners for Grails application servlet context. Feat. HttpSessionListener as a Spring bean example with session timeout depending on whether user account is premium or not.

Common approaches

Speaking of session timeout config in Grails, a default approach is to install templates with a command. This way we got direct access to web.xml file. Also more unnecessary files are created. Despite that unnecessary files are unnecessary, we should also remember some other common knowledge: XML is not for humans.

Another, a bit more hacky, way is to create mysterious scripts/_Events.groovy file. Inside of which, by using not less enigmatic closure: eventWebXmlEnd = { filename -> ... }we can parse and hack into web.xml with a help of XmlSlurper.
Even though lot of Grails plugins do it similar way, still it’s not really straightforward, is it? Besides, where’s the IDE support? Hello!?

Examples of both above ways can be seen on StackOverflow.

Simpler and cleaner way

By adding just a single line to the already generated init closure we have it done:
class BootStrap {

def init = { servletContext ->
servletContext.addListener(OurListenerClass)
}
}

Allrighty, this is enough to avoid XML. Sweets are served after the main course though :)

Listener as a Spring bean

Let us assume we have a requirement. Set a longer session timeout for premium user account.
Users are authenticated upon session creation through SSO.

To easy meet the requirements just instantiate the CustomTimeoutSessionListener as Spring bean at resources.groovy. We also going to need some source of the user custom session timeout. Let say a ConfigService.
beans = {    
customTimeoutSessionListener(CustomTimeoutSessionListener) {
configService = ref('configService')
}
}

With such approach BootStrap.groovy has to by slightly modified. To keep control on listener instantation, instead of passing listener class type, Spring bean is injected by Grails and the instance passed:
class BootStrap {

def customTimeoutSessionListener

def init = { servletContext ->
servletContext.addListener(customTimeoutSessionListener)
}
}

An example CustomTimeoutSessionListener implementation can look like:
import javax.servlet.http.HttpSessionEvent    
import javax.servlet.http.HttpSessionListener
import your.app.ConfigService

class CustomTimeoutSessionListener implements HttpSessionListener {

ConfigService configService

@Override
void sessionCreated(HttpSessionEvent httpSessionEvent) {
httpSessionEvent.session.maxInactiveInterval = configService.sessionTimeoutSeconds
}

@Override
void sessionDestroyed(HttpSessionEvent httpSessionEvent) { /* nothing to implement */ }
}
Having at hand all power of the Spring IoC this is surely a good place to load some persisted user’s account stuff into the session or to notify any other adequate bean about user presence.

Wait, what about the user context?

Honest answer is: that depends on your case. Yet here’s an example of getSessionTimeoutMinutes() implementation using Spring Security:
import org.springframework.security.core.context.SecurityContextHolder    

class ConfigService {

static final int 3H = 3 * 60 * 60
static final int QUARTER = 15 * 60

int getSessionTimeoutSeconds() {

String username = SecurityContextHolder.context?.authentication?.principal
def account = Account.findByUsername(username)

return account?.premium ? 3H : QUARTER
}
}
This example is simplified. Does not contain much of defensive programming. Just an assumption that principal is already set and is a String - unique username. Thanks to Grails convention our ConfigService is transactional so the Account domain class can use GORM dynamic finder.
OK, config fetching implementation details are out of scope here anyway. You can get, load, fetch, obtain from wherever you like to. Domain persistence, principal object, role config, external file and so on...

Any gotchas?

There is one. When running grails test command, servletContext comes as some mocked class instance without addListener method. Thus we going to have a MissingMethodException when running tests :(

Solution is typical:
def init = { servletContext ->
if (Environment.current != Environment.TEST) {
servletContext.addListener(customTimeoutSessionListener)
}
}
An unnecessary obstacle if you ask me. Should I submit a Jira issue about that?

TL;DR

Just implement a HttpSessionListener. Create a Spring bean of the listener. Inject it into BootStrap.groovy and call servletContext.addListener(injectedListener).