2012-05-10 37 views
0

我想在同一个类中使用Selenium webdriver编写两个testng测试 - 一个登录到应用程序和其他人创建一个新帐户。driver.findElement(By.linkText(“”))在一个测试中工作,但在另一个抛出异常

这是我下面 步骤 - 使用@BeforeClass对火狐浏览器中打开应用程序

@BeforeClass 
public void setUp() throws Exception { 
    driver = new FirefoxDriver(); 
    baseUrl = "http://www.salesforce.com"; 
    driver.get(baseUrl + "/"); 
} 
  • 首先测试器登录到网站

    @Test 
    public void testLogin() throws Exception { 
    driver.findElement(By.id("username")).sendKeys(strUsername); 
    driver.findElement(By.id("password")).sendKeys(strPassword); 
    driver.findElement(By.id("Login")).click(); 
    

    }

  • 第二次测试创建一个新帐号

    @Test 
    public void createAccount() throws Exception { 
    driver.findElement(By.linkText("Accounts")).click(); 
    ************************ 
         ************************ 
         ************************ 
         ************************ 
         ************************ 
    

    }

我的问题是,当我运行这个测试TestNG的,我得到异常的第二个测试: org.openqa.selenium.NoSuchElementException:找不到元素:{ “方法”:“链接文本”,“选择器”:“帐户”}

但是,如果我包含命令“driver.findElement(By.linkText(”Accounts“))。click();”在testLogin()测试中,它起作用。我想在同一浏览器会话中运行所有测试。

任何输入将不胜感激。 谢谢。

回答

0

@BeforeClass将为每个单独的测试运行您的设置方法 - 因此对于测试1,将创建一个新的Firefox浏览器并且它将会登录。对于第二个测试,将会创建另一个新的Firefox浏览器,它将尝试查找帐户链接 - 我假设仅在登录时才显示,但第二个浏览器此时不会登录。

你确定你是在@BeforeClass之后吗?

+0

TestNG中,在测试中运行相同的浏览器窗口,但createAccount()方法在login()之前被调用,因此它抛出异常。使用dependsOnMethods解决了这个问题。 – user1387236

1

@BeforeClass对于一个类只运行一次。因此,如果您将两个测试都保存在同一个类中,则执行顺序为@beforeClass,第一个测试用例,然后是第二个测试用例(到达此测试时应可见您的帐户链接)。

测试顺序未被测试。所以,如果帐户链接只有在您登录后才可见,那么您的案件可能并不总是通过。因此,问题可能是

  1. 元素没有出现当到达 或
  2. 的createAccount您的createAccount()测试的时间登录之前被调用,由于该账户链接不可用。

如果您希望您的测试用例按特定顺序执行,请使用dependsOnMethods并使createAccount依赖于testLogin方法。 (请参考Testng Dependent methods

+0

谢谢niharika_neo。 createAccount在testLogin之前运行,所以我得到了异常。使用dependsOnMethods解决了这个问题。 – user1387236

0

我想你的第二个测试方法是先执行。它需要执行第一种方法(用于登录)来获取“帐户”链接。您需要在第二种方法中使用dependsOnMethod,以便testLogin执行1st,然后执行createAccountMethod。您的setUp()方法对于@BeforeClass似乎是可以的。所以,请保持setUp()方法不变。声明其它两种方法:

@Test 
public void testLogin() throws Exception { 
//your code here 
} 
@Test(dependsOnMethods{"testLogin"}) 
public void testCreateAccount() throws Exception { 
//your code here 
} 

在上面的代码TESTLOGIN()将执行第一次,然后testCreateAccount()方法,以便在所需链接点击不会错过

相关问题