cargo maven
开箱即用,可以在Maven中进行单元测试。 因此,它也经常用于集成测试。 这样做的主要缺点是集成测试可能需要花费更多的时间来执行,并且因为没有人喜欢每次构建都要等待很长时间–只是使用-Dmaven.test.skip=true
标志跳过了测试
为了执行与Maven的集成测试,我们应该使用Maven Failsafe插件 。 因此,我们可以通过调用mvn test
或使用mvn verify
执行集成测试来快速运行单元测试。
集成测试应在尽可能与生产环境相似的环境中运行。 如果您的应用程序是WAR或EAR软件包,则可以使用Maven Cargo插件来告诉Maven将其部署在应用程序服务器或servlet容器上,并在已部署的应用程序上执行集成测试。
Maven故障安全插件配置
为了启用集成测试阶段,必须将故障安全插件配置添加到pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">...<build><plugins>...<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-failsafe-plugin</artifactId><version>2.12</version><executions><execution><goals><goal>integration-test</goal><goal>verify</goal></goals></execution></executions></plugin></plugins></build>...
</project>
现在,当调用mvn verify
时,包含测试匹配的所有文件src/test/java/**/*IT.java
将在集成测试阶段执行。
集成测试不过是使用JUnit或TestNG批注的类来告诉Maven哪种方法是测试,并且应该使用与单元测试相同的方式来声明。
Maven Cargo插件配置
Cargo插件支持市场上所有主要的应用服务器 。 在我的示例中,我将使用默认的Apache Tomcat 7安装。
- Tomcat正在集成前阶段启动
- tomcat在整合后阶段处于停止状态
<plugin><groupId>org.codehaus.cargo</groupId><artifactId>cargo-maven2-plugin</artifactId><version>1.2.0</version><configuration><container><containerId>tomcat7x</containerId><zipUrlInstaller><url>http://archive.apache.org/dist/tomcat/tomcat-7/v7.0.16/bin/apache-tomcat-7.0.16.zip</url><downloadDir>${project.build.directory}/downloads</downloadDir><extractDir>${project.build.directory}/extracts</extractDir></zipUrlInstaller></container></configuration><executions><execution><id>start-tomcat</id><phase>pre-integration-test</phase><goals><goal>start</goal></goals></execution><execution><id>stop-tomcat</id><phase>post-integration-test</phase><goals><goal>stop</goal></goals></execution></executions>
</plugin>
效果很好。 现在,当您第一次执行mvn verify
时,您可以看到在集成测试运行之前正在下载并启动Tomcat。
集成测试类示例
现在,我们终于可以编写有用的集成测试了–将检查应用程序是否发送正确的错误代码作为响应。
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;import java.io.IOException;import static org.fest.assertions.Assertions.assertThat;public class CheckApplicationDeployIT {private static final String URL = "http://localhost:8080/myApp/testURL";@Testpublic void testIfAppIsUp() throws IOException {//givenHttpClient client = new DefaultHttpClient();HttpGet httpget = new HttpGet(URL);//whenHttpResponse response = client.execute(httpget);//thenassertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);}
}
当然,集成测试应该更复杂,并且实际上要测试行为。 现在,您可以设置Waitr,Selenium或任何其他满足您最佳需求的解决方案,并创建实际的集成测试。
结论
您是否总是应该在集成测试中测试已部署的应用程序? 它非常有用,但并非总是如此。 如果您的应用程序某种程度上取决于用户的IP地址,则您将无法在不同的请求中对其进行更改。
但是,如果您的应用程序是具有HTML或REST前端的经典Web应用程序,则强烈建议使用。
翻译自: https://www.javacodegeeks.com/2013/12/integration-tests-with-maven-3-failsafe-and-cargo-plugin.html
cargo maven