TestNG @BeforeTest
TestNG @BeforeTest Annotation
当您自动化测试用例时,您有一个要求,您希望首先删除您提交的数据。例如,当您运行测试用例时,您将在表单中填写详细信息,并将数据保存在数据库中。当您再次运行测试用例时,您会收到"数据已经存在"的错误。
@BeforeTest: @BeforeTest 注释会在属于该文件夹的任何测试之前先执行。
让我们通过一个例子来理解。
第一种情况: 当我们将@BeforeTest 注释方法放在开头时。
第 1 步: 打开Eclipse。
第 2 步: 我们创建了两个 java 项目,即 it_department.java 和 hr_department.java。
it_department.java
package com.lidihuo;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class it_department
{
@BeforeTest // annotated method placed in the beginning.
public void before_test()
{
System.out.println("It will be executed first");
}
@Test
public void software_developers()
{
System.out.println("Software Developers");
}
@Test
public void software_testers()
{
System.out.println("Software Testers");
}
@Test
public void qa_analyst()
{
System.out.println("QA Analyst");
}}
在上面的代码中,一个方法被放置在@BeforeTest注解下,它会在it_department中所有可用的测试方法之前首先执行。
hr_department.java
package com.lidihuo;
import org.testng.annotations.Test;
public class hr_department
{
@Test
public void manager()
{
System.out.println("Manager");
}
@Test
public void hr()
{
System.out.println("HR");
}
@Test
public void counsellor()
{
System.out.println("Counsellor");
}
}
第 3 步: 创建 testng.xml 文件。 testng.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<test name="IT Department">
<classes>
<class name="com.lidihuo.it_department"/>
</classes>
</test> <!--Test-->
<test name="HR Department">
<classes>
<class name="com.lidihuo.hr_department"/>
</classes>
</test> <!--Test-->
</suite> <!--Suite-->
第 4 步: 运行 testng.xml 文件。右键单击 testng.xml,然后将光标向下移动到 Run As,然后单击 1 TestNG Suite。
输出
上面的输出显示@BeforeTest注解中的方法在it_department的所有测试用例之前先执行。
第二个例子: 当我们把@BeforeTest注解的方法放在最后。
源代码
package com.lidihuo;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class it_department
{
@Test
public void software_developers()
{
System.out.println("Software Developers");
}
@Test
public void software_testers()
{
System.out.println("Software Testers");
}
@Test
public void qa_analyst()
{
System.out.println("QA Analyst");
}
@BeforeTest
public void before_test() // annotated method placed at the end.
{
System.out.println("It will be executed first");
}
}
在上面的代码中,我们把@BeforeTest注解的方法放在最后。
输出
在上面的输出中,我们得出结论是@BeforeTest 注解的方法先被执行,所以,我们得出的结论是@BeforeTest 注解的方法被放置任何地方,都会先执行。