Archive for the ‘Testing’ Category

Quick note on groovy testing a spock

February 29, 2016 Leave a comment

Been getting to grips with gradle, groovy and spock, on a little project and couldnt figure out how to get the GroovyTestCase power assertions available to spock tests.

So eventually found it you have to add the following import

import static groovy.test.GroovyAssert.*
import static org.assertj.core.api.Assertions.*

this enables you to use the the groovy power asserts (shouldfail, assertFalse, etc ), the other is a fluent assertion library that has some interesting features – you need to update your compile dependencies to include ‘org.assertj:assertj-core:3.0.0’

I have not played with the Hamcrest matchers at this point but probably worth a look as these with Spock too

If you want Gradle to find and run your tests i’ve found its easiest to end your class file nameTest.groovy then you can run single shot tests for example like this

gradle -Dtest.single=DynamicRuleSpecification test

which will run the DynamicRuleSpecificationTest.groovy in your ‘src/test/groovy’ folder

Happy testing

Categories: gradle, Groovy, Testing Tags: ,

On Grails Neo4j and unit integration testing …

March 22, 2014 Leave a comment

Life is never as easy as you imagine …

So first get your grails environment set up, i’m using GGTS 3.5M2 and grails 2.3.7

Create yourself a grails project and wait for all the scripts to finish. Then in your projects /conf/BuildConfig you need to the add the following plugin -> :neo4j:1.1.1, and whilst your at it you need to comment out the database-migration plugin as there is a bug somewhere that stops your integration tests from running. ( i have left the hibernate plugin installed as i am setting the static mapWith clause on the domain classes i want to persist through Neo4j (trying mixed mode persistence and see what happens))

   plugins {
	compile ":neo4j:1.1.1"
        // plugins for the build system only
        build ":tomcat:"

        // plugins for the compile step
        compile ":scaffolding:2.0.2"
        compile ':cache:1.1.1'

        // plugins needed at runtime but not for compilation
        runtime ":hibernate:" // or ":hibernate4:4.3.4"
        //runtime ":database-migration:1.3.8"
        runtime ":jquery:"
        runtime ":resources:1.2.7"
        // Uncomment these (or add new ones) to enable additional resources capabilities
        //runtime ":zipped-resources:1.0.1"
        //runtime ":cached-resources:1.1"
        //runtime ":yui-minify-resources:0.1.5"

        // An alternative to the default resources plugin is the asset-pipeline plugin
        //compile ":asset-pipeline:1.6.1"

        // Uncomment these to enable additional asset-pipeline capabilities
        //compile ":sass-asset-pipeline:1.5.5"
        //compile ":less-asset-pipeline:1.5.3"
        //compile ":coffee-asset-pipeline:1.5.0"
        //compile ":handlebars-asset-pipeline:"

also we’ll start with embeddedGraphDatabase mode – but you still need to inform grails where the backing store is in /conf/DataSource.groovy – else it’ll moan saying it can’t find grails.neo4j configuration if you don’t do this. The directory you point the database in must be writable on your local machine. I added mine just above the environments section in DataSource.groovy like this

grails {
	neo4j {
			type = "embedded"
			location = "users/802518659/Documents/data/neo4j"
			params = []

The plugins user guide can be found here

With that in place – your ready to go. You start as normal and write a domain class – say something like this. Note the mapWith clause to tell grails to use Neo


class Interaction {

String name
//List tasks //declared i wanted a list not a set

static hasMany = [tasks: Task]

static mapWith = “neo4j”

static constraints = {
name nullable:true

Now some quick notes on testing. When you create a domain class GGTS will automatically create a spoc unit test for you (new default in GGTS).

So now some more fun. Spoc is great, and i’ll post something separately about spoc and grails.

For now you need to know a couple of things (and i forgot of course). Grails does lots of Dynamic additions to your domain classes – so what looks simple as you type generates a complex class with loads of extra ‘Grails’ goodness including addTo() methods if you have a one to many defined on the one side.

However, in unit testing mode this embellishment does not take place and you pretty much get your plain POJO. This can be confusing as you imagine that this embellishment always happens. It does in integration and real running (the grails framework is brought up for both ) but not in unit testing

so if you write a test like this for the domain class like this

unit test:InteractionSpec

@Mock (Task) // add this to Mock the collaborator class
class RequestSpec extends Specification {
void “test create”() {

Interaction req = new Interaction (name:”job1”)

assertTrue req.validate() (flush:true) //

def task1 = new Task (name: ‘new task’)
assert task1
assert task1.validate()

req.addToTasks (task1) //fails unit test – cant find addToTasks method


Most disconcerting, So whats going on. Its a unit test so that extra goodness hasn’t been added. This is what i’d forgotten. If you look in the manual it shows you about unit testing a controller say and using the @Mock ([…]) for the domain collaborators. But here your trying to unit test the domain class itself.

Once you get that then there are two ways round it. One the brute force path, is to do the work manually like this

		req.tasks = new HashSet()
		task1.job = req
		req.tasks.add (task1) ) //often have to flush this in unit test else grails wont write immediately

However this is alot of extra work. The other approach is to use the @Mock ([…]) after the @TestFor () like this, and add the domain class and any collaborator classes to the array of classes to Mock. You’ll now note that the respondsTo method assertion now passes, and the whole test will pass.

@Mock ([Interaction, Task])
class InteractionSpec extends Specification {

    def setup() {

    def cleanup() {

    void "test create"() {
		def interaction = new Interaction (name: "first job")
		def task1 = new Task (name:"task1")
		def task2 = new Task (name:"task2")
		assert interaction.respondsTo ("addToTasks")
		def res = (flush: true)
		Interaction thing = Interaction.get (1)
		thing.addToTasks (task1)
		thing.addToTasks (task2)
		def tasks = thing.tasks.collect{}.sort()
		assert == "first job"
		assert thing.tasks.size() == 2
		assert ["task1", "task2"] == tasks

Spring Testing using annotation – how to set it up in your IDE

November 6, 2013 Leave a comment

This took a little while the other day to try and setup testing in a spring project under gradle, and using annotation configuration context.

This is just a quick post on what you need to do

in this mini explore project i’ve been trying to use the Spring-data for mongo project and then write some tests.

i’d got stuck as i didn’t have the right libraries by default in the gradle project and because i was using annotations you have to tell the testing framework where your context is

so very quickly, go into your IDE (i’m using GGTS) and create a project and convert to gradle or create a gradle project

by default this doesn’t enable for groovy which i use so you have to add some extras, and the project template is set for java – but as you can use joint compilation this isnt an issue really.

1. edit the default add the groovy plugin (and remove the java one to keep it simple – the grrovy one runs joint compilation so any groovy and java files get compiled
2. add the eclipse plugin
3. set your compiler version
4. create your dependencies – the one i had missed was spring-test. Without this your spring test annotations wont be found and the project wont compile – testCompile “org.springframework:spring-test:3.1.4.RELEASE”. I checked the release by looking at the project dependency list built by using the spring-data-mongodb dependency at for me that brought in all the spring 3.1.4 files – so i just used the spring-test on the same release
5. you can ignore the wrapper task its not required in the IDE

apply plugin: 'eclipse'
apply plugin: 'groovy'

sourceCompatibility = 1.7
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'MongoSpringData', 'Implementation-Version': version

//project variables
ext {
	spring_data_version = "1.3.2.RELEASE"

repositories {

dependencies {
	compile ("")
	compile 	"cglib:cglib:2.2"
	compile 	"org.slf4j:slf4j-api:1.7.5"
  	compile 	"org.slf4j:slf4j-simple:1.7.5"
   	compile 	'org.codehaus.groovy:groovy-all:2.1.6'
   testCompile group: 'junit', name: 'junit', version: '4.+'
   testCompile "org.springframework:spring-test:3.1.4.RELEASE"

//not sure why i need this ??
task wrapper(type: Wrapper) {
	gradleVersion = '1.8'

test {
    systemProperties 'property': 'value'

uploadArchives {
    repositories {
       flatDir {
           dirs 'repos'

update all the dependencies

then in my simple base code i have a class that builds the spring context like this. Here the application class is both the context bean builder and provides my main entry for my basic app code.

public class Application {

    CustomerRepository customerRepository

	OrderRepository orderRepository

    Mongo mongo() throws UnknownHostException {
        return new Mongo("localhost")

    MongoTemplate mongoTemplate(Mongo mongo) {
        return new MongoTemplate(mongo, "sdata")

    public static void main(String[] args) {...

then we come to the tests – this took a little searching on the web to find how to do this.
since spring 3.1 you can use the @ContextConfiguration – and specify the classes with @configuration.. to load, and the right context loader required to read the file above.

the rest @Before/@After/@Test – are standard Junit constructs. You can now test your code and have DI injection from the container to inject beans into your test classes

there was a useful link here i found that expands on some of this

@RunWith (SpringJUnit4ClassRunner)
@ContextConfiguration (classes=Application.class, loader=AnnotationConfigContextLoader.class)

 class OrderRepositoryTest {

	@Autowired OrderRepository repository
	Order newOrder 
	void setup() {
		def order = new Order ("new order")
		newOrder = (order)
		assert newOrder.order == "new order"
		assert != null
	void teardown() {
	void findAllTest ()
		Order[] orders = repository.findAll ()
		assert orders 
		assert orders[0].order == "order987"
		assert orders.size() == 2
	void findNewOrder () {...

onwards and upwards all yeh testers

Categories: Groovy, Spring, Testing
%d bloggers like this: