2014-05-13 2 views
-2

누구든지 if/else 조건과 함께 사용하려는 다음 시나리오를 도와주십시오. 나는 Testng Eclipse와 함께 java를 사용하고있다.Java Selenium Webdriver를 사용하는 경우

1) 로그인이 성공하여 홈 페이지로 이동하면 시도/catch를하지 마십시오. 2) 로그인에 실패하면 try 블록으로 이동하십시오.

 driver.findElement(By.name("username")).sendKeys(username); 
     driver.findElement(By.name("password")).sendKeys(password); 
     driver.findElement(By.name("login")).submit(); 

     try{ 

     Assert.assertFalse(driver.findElement(By.xpath("//div[@class='errorMsg']")).getText().matches("Username or password incorrect. Try again.")); 
     } 
     catch(Throwable t){ 
      Assert.fail("Username Or Password is Incorrect."); 
     } 
     Assert.assertEquals(actualTitle, title,"Home is not accessible!"); 

답변

0

재사용을 만들 수)이이 iftry-catch을 교체하는 것처럼 간단 할 것,하지만 요소가 없으면 findBy는 예외를 발생하기 때문에, 당신은 적어도 다음과 같은 2

1

접근이 어떤 요소가 발견되지 않는 경우는 null를 돌려줍니다 findElementIfPresent 방법 :

private WebElement findElementIfPresent(WebDriver driver, By by){ 
     try { 
      return driver.findElement(by); 
     } catch (NoSuchElementException e) { 
      return null; 
     } 
    } 

    ... 

    driver.findElement(By.name("username")).sendKeys(username); 
    driver.findElement(By.name("password")).sendKeys(password); 
    driver.findElement(By.name("login")).submit(); 

    // obtain the div which holds the information 
    WebElement errorDiv = findElementIfPresent(driver, By.xpath("//div[@class='errorMsg']")); 


    // if the div exists and it has an authentication-problem messages, fail 
    if(errorDiv != null && errorDiv.getText().matches("Username or password incorrect. Try again.")) 
     fail("Username Or Password is Incorrect."); 
    } 

    // otherwise proceed with additional verifications 
    assertEquals(actualTitle, title,"Home is not accessible!"); 

2) javadoc's suggestion로 가서 elemen의 목록을 반환 findElements(By)를 사용 ts. 목록은 다음 비어있는 경우 특정 경우, 인증, 그렇지 않으면 시험에게 빠른 응답, 숲에 대한

// obtain the list of error divs 
    List<WebElement> errorDivs = driver.findElements(By.xpath("//div[@class='errorMsg']")); 

    // if there is at east one element present 
    if(!errorDivs.isEmpty()){ 
     // pick first one and use as main failure reason 
     fail(errorDivs.get(0).getText()); 
    } 

    // otherwise proceed with additional verifications 
    assertEquals(actualTitle, title,"Home is not accessible!"); 
+0

감사 실패, 성공했다. 귀하의 코드는 완벽하게 보이지만 문제점은 문자 "Username or password incorrect. Try. again."가있는 By.xpath ("// div [@ class = 'errorMsg']입니다. 로그인 페이지에는 항상 존재하지 않습니다. 사용자가 로그인에 실패하면 나옵니다. 정확한 로그인을 위해 webdriver는이 요소를 찾을 수 없습니다. 실제로, 많은 사용자를 동시에 사용하기 위해 Excel을 사용하기 때문에 올바른 로그인 세부 정보와 일부 잘못된 정보가 있습니다. – user3563252

+0

You 옳다면, findElementIfPresent는 요소가 발견되지 않으면 예외를 던집니다. 업데이트 된 응답을 참조하십시오. – Morfic

+0

대단히 감사합니다. 내 시나리오에서 효과가 있습니다. 그러나 Fail과 함께 메시지에 메시지를 추가하려면 errorDivs .get (0) .getText()); 그것은 가능합니까? 코딩에 대해 잘 모르는 사람들이 보고서를 이해하기 쉽게 만듭니다. 현재 index.html (TestNG)을 사용하여 결과를보고 있습니다. – user3563252

관련 문제