Webdriver的硬性和软性断言

时间:2015-11-06 13:53:06

标签: selenium selenium-webdriver webdriver

我是自动化测试的新手,我对断言和验证感到很困惑。因为我正在使用TestNG,根据我的研究,我发现在webdriver中,我们没有验证,我们有硬性和软性的断言。但是当我搜索它时,我会得到所有混合答案。在任何地方我都找不到详细的例子。 对于软断言,我看到有人使用'customverification'但是当我尝试在我的程序中编写它时,我得到错误,要求创建一个类或接口。 有人可以帮助我。我正在通过互联网学习,所以很难得到正确的答案。 感谢

package revision;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;


public class Six {
WebDriver driver=new FirefoxDriver();


  @Test
  public void SandyOne() {
  driver.get("file:///C:/Users/Sandeep%20S/Desktop/Test.html");
Assert.assertTrue(IsElementPresent(By.xpath("//input[@id='custom']")), "tab was missing");
driver.findElement(By.xpath("//input[@id='custom']")).sendKeys("abcd");
  System.out.println("1st program");

  System.out.println("blah 1");
  System.out.println("blah 2");
  }


  public boolean IsElementPresent(By by) {
  try {
      driver.findElements(by);
      return true;
    } catch (org.openqa.selenium.NoSuchElementException e) {
      return false;
    }
}
}

4 个答案:

答案 0 :(得分:1)

如果断言失败,测试将停止,验证测试将继续进行,并记录错误。

理想情况下,每个测试只有一个断言(例如,加载了正确的页面),在这种情况下,验证将用于检查该页面上的信息。 因此,如果未加载正确的页面,则检查页面上的内容是否正确是没有意义的。

您可以获得一个想法和一个视觉示例here

答案 1 :(得分:1)

你的测试可能在这里失败了:

Assert.assertTrue(IsElementPresent(By.xpath("//input[@id='custom']")), "tab was missing");

因为IsElementPresent返回false。避免这种情况的一种方法是:

try {
    Assert.assertTrue(IsElementPresent(By.xpath("//input[@id='custom']")), "tab was missing");
    driver.findElement(By.xpath("//input[@id='custom']")).sendKeys("abcd");
}
catch (AssertionError ae) {
    //ignore
}

但是,捕获错误是非常难看的代码。更好的方法是使用WebDriver.findElements(By by)并检查结果列表是否为空。

答案 2 :(得分:0)

硬断言:一旦发现断言失败,测试执行就会停止。

软断言:即使发现断言失败,测试仍会继续执行。

e.g。你有3个断言语句Assert1,Assert2,Assert3

现在,如果Assert2在硬断言的情况下失败,测试将终止。 在软断言的情况下,它将转移到测试中的下一步,然后终止。

您需要将软断言实例化为:

SoftAssertions softAssertion = new SoftAssertions();

softAssertion.assertTrue(条件,消息)

在你给定的代码片段中,硬断言是有意义的,因为在找到输入框之前你无法移动到下一步发送文本。

答案 3 :(得分:0)

在给定的示例中,您不需要断言元素存在。如果它丢失了,那么findElement方法会抛出一个错误,你会知道它不在那里。

如果您有元素的ID,请使用它而不是xpath。这将使代码更具可读性和更快:

driver.findElement(By.Id("custom")).sendKeys("abcd");

建议使用PageObject模式并选择带注释的元素,而不是直接调用findElement方法,请参阅PageFactory

public class TestPage {
    @FindBy(id = "custom")
    WebElement custom;

    private WebDriver driver;

    public TestPage (WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public TestPage inputCustom(String txt) {
        custom.sendKeys(txt);
        return this;
    }
}
@Test
public void SandyOne() {
    // ...
    TestPage page = new TestPage(driver);
    page.inputCustom("abcd");
    // ...
}
相关问题