Surefire是Maven的一个插件,用于在构建生命周期中执行单元测试。TestNG是一个测试框架,类似于JUnit但提供了更多功能,如分组测试、参数化测试、依赖测试等。
mvn test -Dtest=TestClassName
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<includes>
<include>**/TestClassName.java</include>
</includes>
</configuration>
</plugin>
在测试类中使用TestNG的@Test
注解定义组:
@Test(groups = {"group1", "group2"})
public class TestClass {
@Test(groups = {"fast"})
public void testMethod1() { /*...*/ }
@Test(groups = {"slow"})
public void testMethod2() { /*...*/ }
}
mvn test -Dgroups=fast
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<groups>fast</groups>
</configuration>
</plugin>
mvn test -Dtest=!TestClassName
mvn test -DexcludedGroups=slow
或在pom.xml中:
<configuration>
<excludedGroups>slow</excludedGroups>
</configuration>
原因:
解决方案:
<includes>
<include>**/*.java</include>
</includes>
原因:
解决方案:
@Test(dependsOnMethods = "...")
明确依赖<configuration>
<parallel>methods</parallel>
<threadCount>4</threadCount>
</configuration>
原因:
解决方案:
<configuration>
<useFile>false</useFile>
<printSummary>true</printSummary>
</configuration>
@Test(dataProvider = "data")
public void testMethod(int param) {
// 测试逻辑
}
@DataProvider(name = "data")
public Object[][] provideData() {
return new Object[][] {
{1}, {2}, {3}
};
}
@Test
public void serverStartedOk() {}
@Test(dependsOnMethods = { "serverStartedOk" })
public void method1() {}
@Test(timeOut = 1000)
public void testWithTimeout() {
// 必须在1秒内完成
}
通过合理使用Surefire和TestNG的这些功能,可以显著提高测试效率和开发体验。