Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have an "in-process" Tomcat instance, for testing purposes?

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 :)

like image 628
Adrian Petrescu Avatar asked Nov 16 '12 03:11

Adrian Petrescu


2 Answers

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();
  }
}
like image 123
Arun P Johny Avatar answered Sep 19 '22 16:09

Arun P Johny


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.

like image 22
Michael Avatar answered Sep 21 '22 16:09

Michael