How to run Spock tests for Java project with eclipse and gradle?


Keywords:java 


Question: 

I'm facing troubles with this test execution. I've followed this tutorial: in order to configure my project. But when I run I got the following exception:

Class not found spock.tests.CustomerReaderSpec java.lang.ClassNotFoundException: spock.tests.CustomerReaderSpec at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

I don't know why, because the class is under the following folder, as you can see:

enter image description here

Here's my build.gradle:

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

repositories {
    jcenter()
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.0.5'

    implementation 'com.google.guava:guava:23.0'

    compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '2.0.2.RELEASE'
    compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.0-api', version: '1.0.1.Final'

    testCompile(
            'junit:junit:4.12',
            'org.codehaus.groovy:groovy-all:2.4.11',
            'org.spockframework:spock-core:1.1-groovy-2.4',
            'org.spockframework:spock-spring:1.0-groovy-2.3'
    )

}

task runScript (dependsOn: 'classes', type: JavaExec) {
    main = 'myscript'
    classpath = sourceSets.main.runtimeClasspath
}

test {
    useJUnit {
        includeCategories 'spock.tests.UnitTest'
    }
    testLogging {
        showStandardStreams = true
    }
}

What could be wrong with it?

Edit:

About the tools.

I'm using:

Spring Tool Suite 
Version: 3.9.2.RELEASE
Platform: Eclipse Oxygen.2 (4.7.2)

Plugin for groovy:
Eclipse Groovy Development Tools
Version: 2.9.2.xx-201712201854-e47

Plugin for gradle:
Eclipse buildship
Version: 2.1.2.v20170807-1324

You can clone the project from here:


1 Answer: 

2 problems I can see in your sample project:

1) CustomerReaderSpec is missing "package spock.tests" at the top

2) Dependency "org.springframework:spring-test:5.0.2.RELEASE" is needed in testCompile

Also, be sure the Groovy compiler you have selected for your workspace (Window > Preferences > Groovy > Compiler) matches -- at least major and minor -- the version of groovy-all dependency you are using.

With those changes, I was able to run the spock test.