接口穩定性或者場景穩定性測試,我一般是利用testng寫好用例,然後打包放在性能機器上去執行,根據需求代碼中加些統計資訊。下面給一個例子。
1、用例
首先是在利testng的@Test(invocationCount=num)設定用例行次數,當然也可以在後面調用方法中設定,我這裡是為圖友善。具體場景代碼就不提供了。
public class TestDemo {
protected Log log = LogFactory.getLog(getClass());
@Test(description = "xxx", dataProvider = "demoDataProvider", invocationCount = 100000)
public void testLR(JSONObject p) { .....
2、主類調用方法
這裡的main方法會執行1中的用例。
public class StabilityTest {
public static void main(String[] args) {
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { TestDemo.class });
testng.run();
}
}
3、打包
這裡打包的話我碰到過兩種情況。
第一情況, 測試用例代碼是單獨一個項目;
第二情況, 測試用例代碼和業務代碼在同一項目裡,且是放在test目下,不在main目錄;
先講第一種情況,寫好主類後,然後配置pom.xml檔案。這裡注意把mainClass的路徑寫正确就ok了。
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<!--這部分可有可無,加上的話則直接生成可運作jar包-->
<archive>
<manifest>
<mainClass>com.chen.sigmax.test.TestAddJob</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
然後執行項目根目錄下執行 mvn assembly:assembly,生成帶依賴庫的包target/stabilitytest-1.0-SNAPSHOT-jar-with-dependencies.jar 。java -jar stabilitytest-1.0-SNAPSHOT-jar-with-dependencies.jar即可執行<mainClass>指定的main方法,進而去跑用例。
第二種情況,如果按上面的方式打包的話會找不到主類,因為預設是讀main目錄的類的。首先增加pom.xml配置:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.3</version>
<configuration>
<descriptor>src/main/resources/assembly.xml</descriptor>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>cn.chen.info.qa.at.StabilityTest</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
然後在在resources目錄下建立插件的配置檔案stabilitytest.xml
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>fat-tests</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<useProjectArtifact>true</useProjectArtifact>
<unpack>true</unpack>
<scope>test</scope>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<directory>${project.build.directory}/test-classes</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>**/*.class</include>
</includes>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>
mvn打所包後會在target目錄中生成帶test字尾的jar包stabilitytest-autotest-1.0-SNAPSHOT-fat-tests.jar,idea上先compile後package的。jar包上傳到性能機器,java -jar stabilitytest-autotest-1.0-SNAPSHOT-fat-tests.jar就可以一直跑用例了。
最後,可以在代碼中加一些統計息,如成功次數、執行時間等。這裡可以把用例的執行改成異步調用,這樣也可以模拟并發的情況。