Andrii Abramov Andrii Abramov - 3 months ago 55
Android Question

Running unit tests with Spock framework

I am using:


  • Android Studio 2.1.3

  • Gradle 2.14.1 (I tried with 2.14 also)

  • OpenJDK version "1.8.0_91"



I want to write some Unit tests with Groovy and Spock for sample Android application.

I have already read about RoboSpock.

When I am trying to run simple test:

package a.b.regex

import spock.lang.Specification

class TestSum extends Specification {


def "test adding some numbers"() {

when:
def a = 5 + 4
then:
a == 9

}
}


When I try to run this test in Android Studio I have an error:

Process finished with exit code 1
Class not found: "a.b.regex.TestSum"Empty test suite.


Configurations that I used:

1)

buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.6'
}
}

apply plugin: 'groovyx.grooid.groovy-android'
...
dependencies {
testCompile 'org.robospock:robospock:1.0.0'
}


2)

buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
classpath 'org.codehaus.groovy:groovy-android-gradle-plugin:1.0.0'
}
}

apply plugin: 'groovyx.android'
dependencies {
testCompile "org.codehaus.groovy:groovy-all:2.4.1"
testCompile "org.spockframework:spock-core:1.0-groovy-2.4"
testCompile 'org.codehaus.groovy:groovy:2.4.6:grooid'
}


From the console no tests are run at all.
With testing Java application I have no problem.

Here is the project code where I want to use Spock: GitHub repository

Thankfully to Pieces I found the answer.

You should use the next configurations:

apply plugin: 'groovyx.android'

buildscript {
repositories {
jcenter() // or mavenCentral, etc.
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
classpath 'org.codehaus.groovy:groovy-android-gradle-plugin:1.0.0'
}
}

testCompile 'org.codehaus.groovy:groovy:2.4.7:grooid'
testCompile('org.spockframework:spock-core:1.0-groovy-2.4') {
exclude group: 'org.codehaus.groovy'
exclude group: 'junit'
}

Answer

1) This should work great other than you are using an outdated version of the groovy android plugin. The current version is 1.0.0. The error you are seeing is that you included your tests in androidTest source folder, when they should be included in the test source folder.

2) You do not want groovy-all, and want to exclude that from the spock transitive dependencies as well.

This would look similar to

dependencies {
    testCompile 'org.codehaus.groovy:groovy:2.4.7:grooid'
    testCompile('org.spockframework:spock-core:1.0-groovy-2.4') {
      exclude group: 'org.codehaus.groovy'
      exclude group: 'junit'
    }
  }

Same as the problem with #1 you probably have the source under androidTest folder instead of the test folder.

The androidTest folder is for test that will run on the device, and the test folder if for tests that will run on your machines JVM.

Comments