接口稳定性或者场景稳定性测试,我一般是利用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就可以一直跑用例了。
最后,可以在代码中加一些统计息,如成功次数、执行时间等。这里可以把用例的执行改成异步调用,这样也可以模拟并发的情况。