首页 > 解决方案 > 使用 TestNG,打开两个 URL 而不是一个

问题描述

使用 TestNG,有两种方法,第一种情况有无效的凭据,但在第二种情况下它是有效的。问题是首先打开 URL 并添加无效凭据,然后再次打开 URL 并添加有效详细信息。为什么 URL 打开两次。

@Test(priority = 0)
public void one() {
    driver.findElement(By.xpath(".//*[@id='user_login']")).sendKeys("In Valid email");
    driver.findElement(By.xpath(".//*[@id='user_login_password']")).sendKeys("InValid password");
}

@Test(priority = 1)
public void two() {
    driver.findElement(By.xpath(".//*[@id='user_login']")).sendKeys("Valid");
    driver.findElement(By.xpath(".//*[@id='user_login_password']")).sendKeys("Valid");
}

@BeforeMethod
public void beforeMethod() {
    // Create a new instance of the Firefox driver
    driver = new FirefoxDriver();
    //Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //Launch the Online Store Website
    driver.get("URL");
}

@AfterMethod
public void afterMethod() {
    // Close the driver
    driver.quit();
}

标签: testng

解决方案


@BeforeMethod 将在类中定义的每个 @Test 方法之前调用,因此您可以在代码中看到 2 个名为“void one()”和“void two()”的 @Test 注释,因此您的 URL 将void one() 方法的打开和传递密钥,浏览器将根据 @AfterMethod 注释关闭。

正如@BeforeMethod 在每次@Test 执行之前调用一样,@AfterMethod 将在每次@Test 执行之后调用。

为了单次执行它,您必须使用@BeforeClass注释,以便它会单次调用并且您将获得所需的结果。与执行结束后关闭浏览器类似,您可以使用@AfterClass注释定义它。


推荐阅读