Sunday, December 24, 2017

In-container unit tests (Docker TestNG integration)


With the advent of containerization of applications and the proliferation of micro-services, there arise a need to test containers similar to the way jar’s(java libraries) are tested using unit testing mechanisms. The example below demonstrates one such method that unitizes an environmental variable to trigger a TestNG test suite from outside a container. 

1.  Put in the test trigger code in your applications entry point as shown below,


package org.testngrunner;
import com.beust.jcommander.internal.Lists;
import org.testng.TestNG;
import java.util.List;
public class App
{
public static void main( String[] args )
{
String trigger = System.getenv("EXEC_TYPE");
if(trigger != null) {
if(trigger.equals("TEST")) {
TestNG testng = new TestNG();
List<String> suites = Lists.newArrayList();
suites.add("testng.xml");
testng.setTestSuites(suites);
testng.run();
}
}
else {
System.out.println("--- default execution flow of the component ---");
}
}
}
view raw App.java hosted with ❤ by GitHub


2. Create a container consisting your application jar file(s), make sure all dependencies are available inside the container. In the example project the testng.xml file and a jar consisting of the application and its dependencies are copied into the container.

FROM openjdk:8-jre-slim
# Add the jar with all the dependencies
ADD target/container-testngrunner.jar /usr/share/dumiduh/container-testngrunner.jar
ADD testng.xml /usr/share/dumiduh/testng.xml
WORKDIR /usr/share/dumiduh/
ENTRYPOINT ["/usr/bin/java", "-cp", "container-testngrunner.jar","org.testngrunner.App"]
view raw testngcontainer hosted with ❤ by GitHub


3.  Run the container passing in the environmental variable as show below,


docker container run -e EXEC_TYPE=TEST containertestngsuite:1.0.0
view raw runcontainer.sh hosted with ❤ by GitHub


Find the example code base here[1]. Note that the container is made problematically using the docker main plugin. 

What's in my Bag? EDC of a Tester