I have a Maven-based web app project that generates a WAR to be run in Tomcat. Let's suppose, for the sake of argument, that it's vitally important for that project's unit tests to actually send/receive requests over the network (rather than simply calling servlet methods with a mock request).
Is there any way for my test harness to run an instance of Tomcat in the same JVM, load the current project, and let the test cases hit it on localhost
? Failing that, how would I actually programatically package the current project (along with dependencies) into a WAR so that I could use Cargo to upload it programatically to some other Tomcat instance? Is there any better alternative than just shelling out to mvn
?
I know my request is unusual and unit tests should be more self-contained, etc, but please let's just play along :)
You can use an embedded Tomcat for exactly this purpose. Simply set up a static instance in your test harness, and shut it down at the end. Here's some sample code:
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.junit.AfterClass;
import org.junit.BeforeClass;
public class TomcatIntegrationTest {
private static Tomcat t;
private static final int TOMCAT_PORT = 9999;
@BeforeClass
public static void setUp() throws LifecycleException {
t = new Tomcat();
t.setBaseDir(".");
t.setPort(TOMCAT_PORT);
/* There needs to be a symlink to the current dir named 'webapps' */
t.addWebapp("/service", "src/main/webapp");
t.init();
t.start();
}
@AfterClass
public static void shutDownTomcat() throws LifecycleException {
t.stop();
}
}
Jetty works really well for this purpose. If you're not locked into having to have Tomcat, you could use this quite easily during the integration test phase. Have pre-integration start jetty, and post-integration stop it and you can throw request at your war file because it's running in an actual container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With