【发布时间】:2013-02-04 20:23:53
【问题描述】:
我正试图围绕 Arquillian 展开思考,甚至可能开始在我的项目中使用它。我有一个简单的 Java Web 应用程序,它作为 WAR 部署到 Tomcat。
在我的项目中,我定义了一个ServletContextListener impl,以便在 Tomcat 启动和停止应用程序时执行代码。
我正在尝试编写一个超级简单使用 ShrinkWrap 的 Arquillian 测试类,并且:
- 确认我的捆绑WAR可以部署到Tomcat并启动,不会抛出异常;和
- 可以在应用程序运行后访问一个简单的系统属性(
ServletContextListener检查);和 - 确认当 Tomcat 关闭时,不会抛出异常(干净关闭)
另外,我实现ServletContextListener 的类称为AppLifecycleManager:
public class AppLifeCycleManager implements ServletContextListener {
private String logLevel;
// Injected by Guice, but that's not really relevant for this question.
@Inject
private Logger logger;
// Getter and setter for logLevel and logger
@Override
public void contextInitialized(ServletContextEvent event) {
logLevel = System.getProperty("log.level");
}
@Override
public void contextDestroyed(ServletContextEvent event) {
logger.info("Peacefully shutting down the application.");
}
}
到目前为止,这是我最好的尝试:
@RunWith(Arquillian.class)
public class MyFirstRealIntegrationTest {
@Deployment
public static Archive<?> createDeployment() {
// Haven't figured this part out yet, but for the sake of
// this question lets pretend this returns a properly-packaged
// WAR of my web app, the same that my Ant build currently produces.
}
@Test
public void shouldBeAbleToStartTomcatWithoutExceptions() {
// Given
Archive war = createDeployment();
// When - deploy war to Tomcat container
try {
// ??? how to access/init a Tomcat container?
TomcatContainer tomcat = new TomcatContainer(); // this is wrong
tomcat.start();
} catch(Throwable throwable) {
// Starting the container should not throw exceptions
Assert.fail();
}
}
@Test
public void shouldBeAbleToStopTomcatWithoutExceptions {
// Same setup as above test but stops tomcat and checks for
// thrown exceptions. Omitted for brevity.
}
@Test
public void shouldHaveAccessToSysPropsOnceRunning() {
// Here, deploy to the container and start it.
// Then, confirm that AppLifecycleManager correctly read
// the log.level system property.
// Given
Archive war = createDeployment();
TomcatContainer tomcat = new TomcatContainer();
// When - AppLifeycleManager should now read the system property
tomcat.start();
// Then - make sure log.level was set to "DEBUG" and that it was
// correctly read by AppLifeCycleManager.
Assert.assertTrue(war.getClass(AppLifeCycleManager.class)
.getLogLevel().equals("DEBUG"));
}
}
因此,鉴于我在这里的方法,我立即遇到了几个问题:
- 我不确定如何访问/实例化我的 Tomcat 容器,以便它甚至可以启动/停止
- 我不确定如何从我正在运行/已部署的 Web 应用程序中实际执行测试。在上面的第三个测试中,我使用
war.getClass(AppLifeCycleManager.class).getLogLevel()尝试访问“实时”类实例并检查其logLevel属性的运行时值,但我知道这是错误的。
所以我问:一个身经百战的 Arquillian 老兵将如何编写这 3 个简单的测试,以及如何从 JUnit 测试中对我的“正在运行”的 Web 应用程序执行测试?提前致谢。
【问题讨论】:
标签: java tomcat integration-testing jboss-arquillian