To follow up on my previous post about how to programmatically build a web archive, I propose to look at how to deploy this archive in a Tomcat instance that is embedded into a JUnit test.
As usual, the presented snippets are available in the JEE-6-Demo application. I will first look at the dependencies, then I will show how to configure Tomcat and finally how to start and stop the embedded instance.
The first dependency is the embedded Tomcat core component. JULI which stands for Java Utility Logging Implementation that is the container extension of common logging. The ECJ compiler and JASPER are required to handle JSPs. Of course all these dependencies are scoped to test only.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
The following snippet prepares the embedded instance. The static member
mTomcat references a new instance of Tomcat. As Tomcat still requires a file system to work, a temporary directory is used to put all the temporary files. To that end, we use the
java.io.tmpdir java property.
These variables are shared among the test cases.
1 2 3 4
As we want to use the same Tomcat configuration among all test cases, the initialization is put in a method annotated with
@Before. First, the method sets the port to
0. This tells the engine to choose the port to run on by itself. This is especially useful to avoid starting the embedded Tomcat on a already used port as
8080 for instance.
Then the base directory is set
mTomcat.setBaseDir() to the temporary directory. Without doing that, Tomcat would start in the current directory. The rest of the method configures the way WAR are managed by the engine.
1 2 3 4 5 6 7 8 9 10
The rest of the method builds a reference to a directory (based into the temporary directory) that contains the web application. This directory is deleted if it exists to ensure redeployment of the WAR. Finally, the WAR built as explained there is exported into the temporary directory.
Finally, the web application is added to the Tomcat instance. More specifically, a path
webApp.getAbsolutePath() of the WAR is linked to a context
1 2 3 4 5 6 7 8 9 10 11
Now that Tomcat has been configured, the next step is to start it. We want a fresh Tomcat for each and every test case. This way, a failed test does not have repercussions on the subsequent tests (e.g. session information, memory leaks);
1 2 3 4 5
If necessary, the actual port on which Tomcat has been started can be retrieved using the following snippet.
1 2 3
Finally, after the test, the Tomcat instance is stopped and destroyed clearing the way for the next test.
1 2 3 4 5 6 7 8 9 10