使用testNG运行此代码:
package org.example;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Test1 {
@BeforeMethod(alwaysRun = true)
public void before() throws Exception {
System.out.println("BEFORE, thread ID=" + Thread.currentThread().getId());
}
@AfterMethod(alwaysRun = true)
public void after() throws Exception {
System.out.println("AFTER, thread ID=" + Thread.currentThread().getId());
throw new Exception("Error!");
}
@Test(alwaysRun = true, invocationCount = 3, threadPoolSize = 1)
public void test() throws Exception {
System.out.println("TEST, thread ID=" + Thread.currentThread().getId());
}
}
返回
BEFORE, thread ID=1
TEST, thread ID=1
AFTER, thread ID=1
BEFORE, thread ID=1
AFTER, thread ID=1
BEFORE, thread ID=1
AFTER, thread ID=1
@ Test方法仅第一次运行,此后跳过。相反,如何实现此目标,即避免跳过@Test方法:
BEFORE, thread ID=1
TEST, thread ID=1
AFTER, thread ID=1
BEFORE, thread ID=1
TEST, thread ID=1
AFTER, thread ID=1
BEFORE, thread ID=1
TEST, thread ID=1
AFTER, thread ID=1
结果显示测试按顺序进行,而不是按顺序进行。因此,使用一个线程来运行测试用例的所有3次调用。
如果调用需要并行运行,那么必须在testng.xml文件中设置以下参数:
用于并行运行的工作示例testng.xml文件:
<suite name="Run tests in parallel" parallel="methods" thread-count="3">
<test name="3-threads-in-parallel">
<classes>
<class name="com.company.tests.TestClass"/>
</classes>
</test>
</suite>