Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

unit testing - How to start and stop an Tomcat container with Java?

I have a Maven project that starts a tomcat container for pre-integration-tests (jUnit Tests). Most of my tests require that the web-application under tests is restarted. So I'd like to restart the Tomcat container before each jUnit test is executed.

As for now I use the cargo-maven2-plugin to configure the tomcat container.

So, is it possible to start and stop the container with a java statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, is it possible to start and stop the container with a java statement?

Your use case looks extremely weird (having to restart the container between tests) but let's not discuss this. To answer your question, yes it is possible and this can be done using Cargo's Java API.

To start a Tomcat container and deploy your war, you can do something like this in the setUp() method:

// (1) Optional step to install the container from a URL pointing to its distribution
Installer installer = new ZipURLInstaller(new URL("http://www.apache.org/dist/tomcat/tomcat-6/v6.0.20/bin/apache-tomcat-6.0.20.zip"));
installer.install();

// (2) Create the Cargo Container instance wrapping our physical container
LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory()
        .createConfiguration("tomcat6x"), ContainerType.INSTALLED, ConfigurationType.STANDALONE);
container = (InstalledLocalContainer) new DefaultContainerFactory()
        .createContainer("tomcat6x", ContainerType.INSTALLED, configuration);
container.setHome(installer.getHome());

// (3) Statically deploy some WAR (optional)
WAR deployable = new WAR("./webapp-testing-webapp/target/webapp-testing-webapp-1.0.war");
deployable.setContext("ROOT");
configuration.addDeployable(deployable);

// (4) Start the container
container.start();

And stop it in the tearDown() method.

// (6) Stop the container
container.stop();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...