How do you assert in WebDriver

最近自动化已经跑起来了,但是感觉不管怎样,他都能过,没有个判断。

在RFS里面,可以调用关键字,看元素是否存在,页面是否打开。但是Webdriver里面,就没有那么好了。

我知道可以用assert,但是用得不熟,网上google了下,大概都是这么用的

try {

          Assert.assertTrue(driver.findElement(By.cssSelector("thislink")).isDisplayed());

       } catch (Exception e) {

           e.printStackTrace();

           throw new Exception("this link isnot displayed");

}

 

源文档 <https://groups.google.com/forum/#!topic/webdriver/wH1KYGQuFF4>

 

看作者的意思,以上方法不好使,只好自己定义一个如下的方法来判断

 

that is my method:

public booleanisElementPresent(By by) {

       try {

           driver.findElement(by);

           return true;  // Success!

       } catch (NoSuchElementException ignored) {

           return false;

       }

    }

 

如下的代码也是,判断不好用,自己定义

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.*;

import org.junit.Before;
import org.junit.After;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

publicclass selftechyTestng
{
   
privateWebDriver driver;
   
privateString baseUrl;

@Before
   
publicvoid setUp() throwsException
   
{
        driver = newFirefoxDriver();
       
baseUrl = "http://selftechy.com/";
       
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
   
}

//First Test Method
      
@Test
   
publicvoid searchElements() throwsException{
       
driver.get(baseUrl);
        driver.findElement(By.xpath("//a[@title='Selenium']")).click();

}

@Test
   
publicboolean isTextPresent(StringtxtValue){
        
try{
            
boolean b =driver.getPageSource().contains(txtValue);
            
return b;
        
}
         catch (Exception e){
            
returnfalse;
        
}
         Assert.IsTrue(isTextPresent("TestNG (Next Generation Testing Framework) – UnderstandingAnnotations"));

}

}

Modification I have done to makethe call to the function isElementPresent work AddingassertTrue() method within searchElements() methods

 assertTrue(isTextPresent(txtValue));

Method isElementPresent

public boolean isTextPresent(String str1)
   
{
         try
         {
            driver.get(baseUrl);
            driver.findElement(By.xpath("//a[@title='Selenium']")).click();
             b =driver.getPageSource().contains(str1);

if(b){
                
System.out.println("text presented on the page");
             }
             else{
                System.out.println("text did not present on thepage");
             }
             return b;
         }
         catch (Exception e)
         {
             System.out.println(e.getMessage());
             return b;
         }

//return b;
    
}

 

源文档 <http://stackoverflow.com/questions/16661699/webdriver-verify-text-presentation-on-a-loaded-page>

 

public boolean isTextPresent(StringtxtValue){
        
boolean b = false;
     try{
         b = driver.getPageSource().contains(txtValue);
         return b;
     }
     catch (Exception e){
         System.out.println(e.getMessage());
     }    
     finally{
      return b;
     }
}

Then your test will look like this

 @Test
public void searchElements() throws Exception{
    driver.get(baseUrl);
   driver.findElement(By.xpath("//a[@title='Selenium']")).click();
   Assert.IsTrue(isTextPresent("TestNG (Next Generation TestingFramework) – Understanding Annotations"));
}

 

 

我还看到

The following is from the DOM before the checkbox is selected:

<input type="checkbox" id="c234" name="instantAd" value="true" class="t-checkbox-A">

Then, once the checkbox becomes selected a 'checked' is added, like so:

<input type="checkbox" id="c234" name="instantAd" value="true" checked="" class="t-checkbox-A">

I have tried the following:

WebElement checkBox = chrome.findElement(By.cssSelector("input.t-checkbox-A[name=\"instantAd\"]"));

new WebDriverWait(chrome, 5).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.t-checkbox-A[name=\"instantAd\"]")));

Assert.assertEquals("null",checkBox.getAttribute("checked"));

checkBox.click();

Assert.assertEquals("true",checkBox.getAttribute("checked"));

The first assertion fails. Perhaps this is because the 'checked' attribute isn't visible in the DOM yet, at a guess.

The stacktrace is displaying:

java.lang.AssertionError: expected: java.lang.String but was: null

I've searched many different posts but none offer me the answer Im looking for, and when checkinghttp://junit.sourceforge.net/javadoc/org/junit/Assert.html for info and guidance (as being new to test automation, Im finding it difficult to work out what I need in my constructor.

Any help would be most appreciated.


 

 

 

1

Try using the '.isSelected()` method instead. So verify via assertTrue rather than assertEquals. That's how we do it in Python, I imagine it would be similar in Java? –  Mark Rowlands Dec 11 '13 at 15:11

add comment

2 Answers

activeoldestvotes

up vote0down vote

There is a less preferable way to achieve the goal, than @mark suggested. (For cases when isSelected() does not work).

boolean isFound = false;
try {
 
isFound = driver.findElement(By.cssSelector("input.t-checkbox-A[name=\"instantAd\"][checked]")).isDisplayed();
} catch (NoSuchElementException e) {
// Do nothing
}
Assert.assertFalse(isFound);
checkBox.click();
try {
  isFound = driver.findElement(By.cssSelector("input.t-checkbox-A[name=\"instantAd\"][checked]")).isDisplayed();
} catch (NoSuchElementException e) {
// Do nothing
}
Assert.assertTrue(isFound);

In short, the code tries to verify if the element with the "checked" attribute is displayed. If it is, then isFound is set to true, else isFound remains false

There are disadvantages:

  • too much code
  • the test will spend additional 5 seconds before throwing the NoSuchElementException when the element is not found

The "try" clause can be externalized to a separate method.

 

源文档 <http://stackoverflow.com/questions/20522018/asserting-a-checkbox-is-not-checked-by-default-in-webdriver-with-junit>

 

如下的代码,用assertEquals()来判断getText()和期望的是否相等

When we start making some  web application, Westart with some UI and Every UI has menu, Check box, Button, Combo Box , Radiobutton, Text Field and other element of Web Application.

But most of the time we need toverify that Text or value associated with above mentioned elements of WebApplication are correct or not and for this we commonly use two function

1- getText()

2- assertEquals().

getText() helps in retrieving the Textfrom an element by using WebElement class.This method returns the value of inner text attribute of Element.

So why not take a look on thishow it works

packagecom.testng.src.com.testng;

import org.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.chrome.ChromeDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.ie.InternetExplorerDriver;

importorg.openqa.selenium.safari.SafariDriver;

import org.testng.Assert;

importorg.testng.annotations.BeforeMethod;

importorg.testng.annotations.Test;

public class Verify {

WebDriver driver;

@BeforeMethod

public void launch()

{

System.setProperty("webdriver.chrome.driver","E:\DDMISHRA\workspace\chromedriver_win_26.0.1383.0\chromedriver.exe");

driver = new ChromeDriver();

}

@Test

public void verify()throwsException

{

driver.get("http://google.co.in");

WebElement element =driver.findElement(By.xpath("//span[text()='Google Search']"));

String strng =element.getText();

System.out.println(strng);

Assert.assertEquals("GoogleSearch", strng);

}

}

In this script

1- I have used xpath to findthe Google Search button

2- By using findElement methodwe could find Google Search Button

3- Once we get the element, Byusing getText() method we could find the text on Button

4- By using assertEquals(), weverify that Google Search Text is available on Google Search Button. If textretrieved from getText() match with the String inserted in to asserEquals()method then test is passed otherwise it is  failed.

Result after execution of thiscode

Started ChromeDriver

port=22048

version=26.0.1383.0

log=E:DDMISHRAworkspaceDataDrivenWebdriverchromedriver.log

Google Search

PASSED: verify

===============================================

Default test

Tests run: 1, Failures: 0,Skips: 0

===============================================

===============================================

Default suite

Total tests run: 1, Failures:0, Skips: 0

===============================================

There are other assert methodsthat could be used to verify the text in place of assertEquals()

assertTrue(strng.contains(Search));

assertTrue(strng.startsWith(Google));

assertTrue(strng.endsWith(Search));

If this text pattern match thentest get passed other wise test get failed.

 

源文档 <http://www.abodeqa.com/2013/02/23/how-to-use-assertequals-in-webdriver-using-driver-gettext/>

 

 



你可能感兴趣的:(How do you assert in WebDriver)