The challenge here is to pack a “stand alone” java test in an executable jar without losing other execution options for the test, like mvn test and execution from IDE.

Benefits

One of the most common points of discussion when starting the development of a test automation project is: how will the tests be distributed and executed? When working with Java, an executable JAR could be a good option to solve this. The benefits of taking this approach are:

Assumptions

We are dealing with a “stand alone” test, meaning we don’t have a main source code to test in the same project. Instead, the test source code contains all that is required to execute the test. A common scenario is a UI functional testing of a web app using Selenium, where we just need access to the app through a URL, and all the page classes and tests are contained in a single source of code.

Also, this implementation considers maven keeps the default directory structure:

src/main/java

src/main/resources

src/test/java

src/test/resources

There are two approaches that can be used:

A. Test code is in “main”

  1. The test code and resources are contained in (or moved to) the main module src/main/java and src/main/resources
  2. Create a Main class where you can start the execution from. Example:
public class TestMainRunner {
    public static void main(String[] args) {

        String[] cucumberArgs = new String[] {
                "-g","steps",
                "classpath:features",
                "-p", "pretty"
        };

        Main.run(cucumberArgs);
    }
}
  1. Add maven-assembly-plugin to pom.xml to enable creating a .jar file including the project dependencies and also to specify the main class to be executed when running the .jar:
<build>
<plugins>
...
	<plugin>
	    <artifactId>maven-assembly-plugin</artifactId>
	    <executions>
	        <execution>
	            <phase>package</phase>
	            <goals>
	                <goal>single</goal>
	            </goals>
	        </execution>
	    </executions>
	    <configuration>
	        <archive>
	            <manifest>
	                <addClasspath>true</addClasspath>
	                <mainClass>run.TestMainRunner</mainClass>
	            </manifest>
	        </archive>
	        <descriptorRefs>
	            <descriptorRef>jar-with-dependencies</descriptorRef>
	        </descriptorRefs>
	    </configuration>
	</plugin>
...
</build>
</plugins>

To generate the .jar file run from terminal: