解决TestNG测试用例依赖性的问题

时间:2022-09-07 12:36:23

如果测试用例间有依赖性,也就是如果想执行B,就必须要先执行A。那么用例的执行顺序就很关键,如何来指定用例的顺序呢,有这样几种方法:

1. 给用例加编号:

public void test01Login(){

XXX

}

public void test02Add(){

XXX

}

public void test03Delete(){

XXX

}

2. 加上关键字

硬依赖的例子:
@Test
public void serverStartedOk() {}
@Test(dependsOnMethods = { "serverStartedOk" })
public void method1() {}
此例中,method1() 依赖于方法 serverStartedOk(),从而保证
serverStartedOk() 总是先运行。

 

public class Demo1 {
	WebDriver driver;
	
	@BeforeClass
	public void beforeClass() {
		System.setProperty("webdriver.ie.driver","E:\\WebDriver\\IEDriverServer.exe");
		driver = new InternetExplorerDriver();
	}
	//登录博客
	@Test
	public void login() throws InterruptedException {
		System.out.println("login开始执行了");
		driver.get("http://blog.ifeng.com");
		driver.findElement(By.id("username")).sendKeys("itest20");
		driver.findElement(By.id("password")).sendKeys("123456");
		driver.findElement(By.xpath("//input[@value='登录']")).click();
		driver.navigate().refresh();
	}
	//验证标题是否为空
	@Test(dependsOnMethods = { "login" })
	public void noSubject() throws InterruptedException{
		System.out.println("noSubject开始执行了");
		driver.get("http://blog.ifeng.com");
		String originalHandle = driver.getWindowHandle();
		driver.findElement(By.linkText("发表博文")).click();
		for(String winHandle: driver.getWindowHandles()){
			if(winHandle!=originalHandle)
				driver.switchTo().window(winHandle);
			driver.manage().window().maximize();
		}
		Thread.sleep(2000);
		Assert.assertTrue(FindElement.isElementExist(driver, By.id("saveArticle")));
		driver.findElement(By.id("saveArticle")).click();
		//判断当标题为空时提示是否正确
		boolean expected = true;
		boolean actual = (driver.findElement(By.id("blog_tishi")).getText()).endsWith("请填写文章标题");
		Assert.assertEquals(actual, expected, "标题为空");
		Thread.sleep(3000);
	}
	//验证内容是否为空
	@Test(dependsOnMethods = { "noSubject" })
	public void noContent() throws InterruptedException{
		System.out.println("noContent开始执行了");