Running both Spock Unit Tests and TestNG Integration Tests in Maven

Spock, TestNG and maven

I use maven and TestNG for most of my Selenium automation tests. I wanted to add some Spock unit tests (because Spock tests are awesome). But found that they would not run together. Spock generates JUnit tests but my setup was trying to run TestNG tests.

Solution

You need to tell maven to run the Spock tests as JUnit tests. To do this, add the maven plugins to compile and run your Spock tests as usual but also add the surefire-junit47 dependency to the maven-surefire-plugin.

See below for the annotated sections of the pom.xml file:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.5.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>  
    <!-- Unit tests -->
    <plugin>
      <!-- Compiles Groovy code. -->
      <groupId>org.codehaus.gmavenplus</groupId>
      <artifactId>gmavenplus-plugin</artifactId>
      <version>1.5</version>
      <executions>
        <execution>
          <goals>
            <goal>compile</goal>
            <goal>testCompile</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <!-- Run Spock Tests -->
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.19.1</version>
      <configuration>
        <includes>
          <include>*/*Spec.*</include>
        </includes>
      </configuration>
      <!-- Run Spock tests with JUnit not TestNG -->
      <dependencies>
        <dependency>
          <groupId>org.apache.maven.surefire</groupId>
          <artifactId>surefire-junit47</artifactId>
          <version>2.19.1</version>
        </dependency>
      </dependencies>
    </plugin>
    <!-- Integration tests using failsafe-plugin -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-failsafe-plugin</artifactId>
      <version>2.19.1</version>
      <configuration>
        <parallel>methods</parallel>
        <includes>
          <include>**/*Test.java</include>
          <include>**/*Tests.java</include>
        </includes>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>integration-test</goal>
            <goal>verify</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>