我的脚本在java类中工作正常,但是当我使用testng时,相同的脚本失败了。它只是打开浏览器并使我的脚本失败

时间:2017-03-23 09:38:21

标签: selenium testng

请找到以下代码:我执行了以下步骤,但没有奏效。 请帮助:

public class ForSe_TestCases        
public WebDriver driver;    

@BeforeTest     
public void setup ()    
{          
System.setProperty("webdriver.chrome.driver", "path");
WebDriver driver =new ChromeDriver();               
driver.manage().deleteAllCookies();          
} 

@Test(priority = 0)     
public void Validlogin_IO () throws InterruptedException {
driver.navigate().to("http://**URL**"); 
driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Pass12345");
driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();    
System.out.println("Login button pressed");
}       

TestNG会出现什么问题?

3 个答案:

答案 0 :(得分:0)

尝试以下任何/所有

  1. 删除并再次将TestNG jar添加到您的项目构建路径
  2. 安装并重新安装TestNG插件
  3. 清理Eclipse项目并重新运行。
  4. 如果无效则试试这个:

     public static void main(String[] args) {
            TestListenerAdapter tla = new TestListenerAdapter();
            TestNG testng = new TestNG();
            testng.setTestClasses(new Class[] { YOURCLASSNAME.class });
            testng.addListener(tla);
            testng.run();
    }
    

    代替YOURCLASSNAME提供包含@Test注释的类名。这就像在没有main方法插件的情况下运行测试一样。

答案 1 :(得分:0)

更新至Chrome驱动程序2.28,将Google Chrome浏览器更新至57.x,将Selenium更新至3.x.x。您还必须在打开浏览器之前设置Chrome驱动程序的路径。

router

检查此代码。此代码成功打开了google.co.in

执行此文件“Run As TestNG Test”

如果这有助于您,请告诉我。

答案 2 :(得分:0)

Sanchit,我认为它失败是因为你没有等待元素出现在页面上而webDriver(比它的阴影更快!)认为你想要找到的第一个元素不在那里( ID =' EMAIL_ADDRESS)

尝试阅读here以隐式或显式方式等待或使用下面的代码(如果元素存在则方法返回true):

public boolean waitForElement(String elementXpath, int timeOut) {

    try{                    
    WebDriverWait wait = new WebDriverWait(driver, timeOut); 
    boolean elementPresent=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(elementXpath)).isDisplayed());

    System.out.printf("%nElement is present [T/F]..? ")+elementPresent;
    }        
    catch(TimeoutException e1){e1.printStackTrace();elementPresent=false;}          

    return elementPresent;   
 }
OP的评论后

更新

要查看我的方法是否有效,请尝试替换您的第一个查找元素行:

driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com"); //this is official email 

使用下面的代码代替(如果它确实使用这种等待方法来破坏'元素,那么你的脚本将不会从那时起打破)。我认为您的脚本会立即打破,因为您可以非常快速地找到元素和sendKeys,而无需等待它首先出现!

waitForElement ("//*[@id='email_address']", 10);
if(elementPresent==true){
driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com");
}
else{
System.out.println("FATAL! Couldn't locate email address field!");
}

希望你这次能破解它!