java - 如何使用 Java 启动和停止 Tomcat 容器?

标签 java unit-testing tomcat maven-2 junit

我有一个 Maven 项目,它启动一个 tomcat 容器用于预集成测试(jUnit 测试)。我的大部分测试都需要重新启动被测 Web 应用程序。所以我想在执行每个 jUnit 测试之前重新启动 Tomcat 容器。

至于现在我使用 cargo-maven2-plugin 来配置 tomcat 容器。

那么,是否可以通过java语句启动和停止容器呢?

最佳答案

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

您的用例看起来非常奇怪(必须在测试之间重新启动容器)但我们不讨论这个。要回答你的问题,是的,这是可能的,这可以使用 Cargo 来完成。的 Java API。

要启动一个 Tomcat 容器并部署你的 war,你可以在 setUp() 方法中做这样的事情:

// (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();

并在 tearDown() 方法中停止它。

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

关于java - 如何使用 Java 启动和停止 Tomcat 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2190300/

相关文章:

java - spring junit默认会回滚吗?

c# - 从命令行运行 MSTest 时出现 Fluent Nhibernate 异常

c++ - 在 Visual Studio 中进行适当的单元测试

android - 使用 Mockito 模拟改造服务导致 ExceptionInInitializerError

java - tomcat启动但没有监听任何端口

java - 带条件(真或某些原因导致 NPE)的 Hibernate 选择列表不返回任何结果

java - Hibernate:创建表异常

java - JMockit:覆盖@Mocked类

java - 想了解有关Java Servlet的信息。

java - 为什么访问 Tomcat 上的文件(使用 HttpServlet)时得到空指针?