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,
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ---"); | |
} | |
} | |
} |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] |
3. Run the container passing in the environmental variable as show below,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
docker container run -e EXEC_TYPE=TEST containertestngsuite:1.0.0 |
Find the example code base here[1]. Note that the container is made problematically using the docker main plugin.