8. 分组测试
分组测试即为使用group,如果你使用xml的话就是里边的<groups>标签,如果是直接在class中,是通过@Test(groups="group2")这种方式来分组,如第四节的注解说明中的那个例子,分了两个group,而且@BeforeGroup是需要添加group名称才可以正确挂载到该group下的;
这个group说明可以是在单个的测试方法上,也可以在class上,只要具有同样的group名称都会在同一个group中,同时group名称可以有多个,类似@Test(groups = {"mysql","database"})这种,范例如下:
一个测试文件NewTest.class:
```
public class NewTest {
@Test(groups="group1")
public void test1() {
System.out.println("test1 from group1");
Assert.assertTrue(true);
}
@Test(groups="group1")
public void test11() {
System.out.println("test11 from group1");
Assert.assertTrue(true);
}
@Test(groups="group2")
public void test2()
{
System.out.println("test2 from group2");
Assert.assertTrue(true);
}
@BeforeTest
public void beforeTest()
{
System.out.println("beforeTest");
}
@AfterTest
public void afterTest()
{
System.out.println("afterTest");
}
@BeforeClass
public void beforeClass()
{
System.out.println("beforeClass");
}
@AfterClass
public void afterClass()
{
System.out.println("afterClass");
}
@BeforeSuite
public void beforeSuite()
{
System.out.println("beforeSuite");
}
@AfterSuite
public void afterSuite()
{
System.out.println("afterSuite");
}
@BeforeGroups(groups="group1")
public void beforeGroups()
{
System.out.println("beforeGroups");
}
@AfterGroups(groups="group1")
public void afterGroups()
{
System.out.println("afterGroups");
}
@BeforeMethod
public void beforeMethod()
{
System.out.println("beforeMethod");
}
@AfterMethod
public void afterMethod()
{
System.out.println("afterMethod");
}
}
```
另一个TestCase1.class:
```
@Test(groups= "group2")
public class TestCase1 {
@Test(enabled=false)
public void TestNgLearn1() {
System.out.println("this is TestNG test case1");
}
@Test
public void TestNgLearn2() {
System.out.println("this is TestNG test case2");
}
}
```
xml如下:
```
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
<test name="Test">
<groups>
<include name="group1"></incloud>
<include name="group2"></incloud>
</groups>
<classes>
<class name="com.demo.test.testng.NewTest"/>
<class name="com.demo.test.testng.TestCase1"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
```
运行结果如下:
```
beforeSuite
beforeTest
beforeClass
beforeGroups
beforeMethod
test1 from group1
afterMethod
beforeMethod
test11 from group1
afterMethod
afterGroups
beforeMethod
test2 from group2
afterMethod
afterClass
this is TestNG test case2
afterTest
afterSuite
```
如上所示,先运行了group1的两个用例,再运行group2的两条用例;
注意在xml标识group,需要将要运行的group加进来,同时还要将被标识这些group的class也加进来,不被加进去的不会运行。