在selenium中捕获客户端验证消息(testng)

时间:2016-04-21 13:53:09

标签: java selenium selenium-webdriver testng

site image我想捕获在文本框中输入无效输入后生成的消息(以文本形式显示)。单击其他文本框或仅在屏幕上显示此消息。此文本具有分配给它的id,但在输入无效输入时会在运行时显示,否则不显示。

这是代码行

driver.findElement(By.id("ctl00_CenterCPH_txtCityName")).sendKeys(c.cityname);

因为,我在testng中使用@dataProvider传递多个输入,所以我可能有正面和负面结果。所以在负面结果的情况下我想捕获在客户端和后面生成运行时的错误消息将它提取到报告中。到目前为止,我只能获取服务器端错误消息,难以获取客户端错误消息。

我附上了网站观看源的图片,

提前致谢 网站图片view source of the site

2 个答案:

答案 0 :(得分:0)

嗨,请按照下面的说法进行操作

public class CapturingErrorMessage {
    public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.get("ur url");

        // suppose u entered wrong i.e more then 128 character string in the input box

        driver.findElement(By.id("ctl00_CenterCPH_txtCityName")).sendKeys("more then 128 character");

        // talking under consideration that error message is displayed when you click on other textbox or simply on the screen.

        // suppose below line is to click on other option or some where on the screen 
        driver.findElement(By.id("ctl00_CenterCPH_txtCityName")).click();

        // now error message comes so before capturing the error message firstly try to 
        // identify if the span id with error message is present or not

        // simply in the if i am checking that if the size of the span tag with error is more then 0 or not if more then zero 
        // i.e error is present on the page
        if(driver.findElements(By.id("ct100_CenterCPH_revAlphaNum1Len")).size() > 0){
            String error = driver.findElements(By.id("ct100_CenterCPH_revAlphaNum1Len")).get(0).getText();
            System.out.println(error);
        }else{
            System.out.println("Element not present :  no error message");
        }   
    }
    }

希望这会对你有所帮助

答案 1 :(得分:0)

我认为您可以使用 ExpectedConditions.not.invisibilityOfElementWithText 来解决此问题,因为无论DOM的可见性如何,使用 presenceOf 都会返回true:

public static final By INVALID_CITY_NAME = 
   By.xpath(".//span[ends-with(@id,'CenterCPH_txtCityName");
  ...
public static boolean waitForTextToAppear(String textToAppear, By locator,
   int timeoutSeconds)
{
    WebDriverWait wait = new WebDriverWait(driver,timeoutSeconds);
    return wait.until(
       ExpectedConditions.not.invisibilityOfElementWithText(locator, textToAppear)
    );
}

然后这样称呼它:

boolean visible = waitForTextToAppear(INVALID_CITY_NAME, "Invalid City name.", 10);

我还没有尝试过,但我认为它会起作用。如果没有,对代码进行小幅调整就可以解决问题。