关于Selenium测试的相关笔记

单位里需要自动化测试,于是就抽空看了下selenium相关的东西。也是第一次接触这些东西。就记录一些个人感觉重要的内容,以免自己今后忘记。
官网上的资料并不多,主要是分成了Selenium WebDriver和老版本的Selenium RC。
1.关于locator,
效率最高的就是通过id的方式锁定web element。
但是公司用了gwt-ext,所有的element都是js自动生成的。每次刷新id都会不同。
所以这个locator我纠结了很久,最后在某人的笔记中发现可以用xpath的text()方法进行锁定。于是问题就迎刃而解。
这里就记录一些比较有用的xpath表达式。
1. 根据文字内容来确定结点,去除文字中的空格。
//td[@jsxtype="text"]/div[contains(normalize-space(text()), 'app3')]

2. 查找父级元素
//div[@class="abc"]/..

3. focus, mouseOver, click连用,某些时候,点击事件无效的时候可以试试

focus | //span[@label="applications"] |
mouseOver | //span[@label="applications"] |
click | //span[@label="applications"] |

4. Selenium 去前后空格后验证 (正则表达式)
//a[contains(text(),"name")]/following::td[1][normalize-space(text())='Text Box']

5. Selenium 用带正则表达式的 replace 来 替换 字符
store | https://xx.com//g.php?t=xxx | url
storeEval | “${url}”.replace(/&/g,”*”) | urlResult
echo | ${urlResult} |

6. waitForXXX,不好使的时候,就先Pause暂停一段时间。

7. type 不好使的时候,试试命令组合 focus, type, fireEvent(blur)

xpath的查找插件Firefinder。

虽然xpath很好用,但是并不是selenium在每个浏览器中都支持这个。
selenium 2.0 webdriver中,firefox的支持还行,ie和htmlunit多不敢恭维,chrome公司里不能用。

selenum 1.0 RC,对ie也支持了xpath,其他浏览器为实践过。

下面贴一个webdriver remote的例子。
package selenium.usecasemap;

import static org.junit.Assert.fail;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import junit.framework.Assert;

import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


/**
 * 
 * 
 */
public class TestUseCaseFundMapping
{
    static Logger LOGGER = Logger.getLogger(TestUseCaseFundMapping.class);
    private static WebDriver driver;
    private String baseUrl;
    private StringBuffer verificationErrors = new StringBuffer();
    private JdbcTemplate jdbcTemplate = null;
    private JdbcConnectionResource connectionResource = null;
    private String queryFirstly = "select 马赛克;
    private String initSql9 = "insert 马赛克";
    private String initSql8 = "insert into 马赛克";
    private String deleteUsecaseSql = "delete 马赛克";
    private String deleteFundMap = "delete 马赛克";

    public void loadConfig()
    {
	System.setProperty("FAW.xxxxxx.bootstrap.config.source", "xml");
	FrameworkContainer.create("xx", "selenium_test");
	connectionResource = ContextManager.getObject("connectionResource", JdbcConnectionResource.class);
	jdbcTemplate = new JdbcTemplate(connectionResource);
    }

    @Before
    public void setUp() throws Exception
    {
	remoteDriverServer();

	baseUrl = "http://马赛克:9980/xxxxweb";
	loadConfig();

    }

    private void remoteDriverServer() throws MalformedURLException
    {
	// DesiredCapabilities capabilities = new DesiredCapabilities();
	// capabilities.setBrowserName(BrowserName.FF.toString());
	// capabilities.setVersion(version)
	// CommandExecutor executor = new HttpCommandExecutor(new
	// URL("127.0.0.1/wd/hub"));
	driver = new RemoteWebDriver(new URL("127.0.0.1/wd/hub"), DesiredCapabilities.firefox());
	// DRIVER = NEW FIREFOXDRIVER();
    }

    /**
     * test add new one
     * 
     * @throws Exception
     */
    @Test
    public void testUsecaseMapping() throws Exception
    {

	finishWork();

	LOGGER.info("finish work done");

	initWork();

	LOGGER.info("init work done");

	login();

	LOGGER.info("login work done");

	openTab();

	LOGGER.info("openTab work done");

	addNew();

	LOGGER.info("addNew work done");

	varifyAddNew();

	LOGGER.info("varifyAddNew work done");

	editPilot();

	LOGGER.info("edit work done");

	varifyEdit();

	LOGGER.info("varify work done");

	testClone();

	LOGGER.info("clone work done");

	varifyClone();

	LOGGER.info("varyfy work done");

	finishWork();

	LOGGER.info("finish work done");
    }

    private void varifyClone()
    {
	driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
	By by = By
		.xpath("//tr/td/div[contains(text(),'UI TEST8')]/../../td/div[contains(text(),'IBWW')]/../../td/div[contains(text(),'On')]");

	WebElement el2 = varifyGetElementByLocator(by);
	Assert.assertNotNull(el2);
    }

    private void testClone() throws InterruptedException
    {
	getElementByLocator(By.xpath("//tr[td[div[contains(text(),'UI TEST9')]] and td[div[contains(text(),'IBWW')]]]/td[1]"))
		.click();
	getElementByLocator(By.xpath("//button[contains(text(),'Clone')]")).click();
	Thread.sleep(1000);
	getElementByLocator(By.xpath("//input[contains(@id,'FUND')]/../input[2]")).sendKeys("ALL");
	driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
	getElementByLocator(By.xpath("//div[contains(text(),'ALL') and contains(@class,'x-combo-list-item')]")).click();
	Thread.sleep(1000);
	getElementByLocator(By.xpath("//div[contains(text(),'UI TEST8')]")).click();

	getElementByLocator(By.xpath("//button[text()='>']")).click();

	getElementByLocator(By.xpath("//button[text()='Save']")).click();

	(new WebDriverWait(driver, 10)).until((ExpectedConditions.presenceOfElementLocated(By.xpath("//button[text()='Yes']"))));

	getElementByLocator(By.xpath("//button[text()='Yes']")).click();
    }

    private void varifyEdit() throws InterruptedException
    {
	driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
	By by = By
		.xpath("//tr/td/div[contains(text(),'UI TEST9')]/../../td/div[contains(text(),'IBWW')]/../../td/div[contains(text(),'On')]");
	WebElement el2 = varifyGetElementByLocator(by);
	Assert.assertNotNull(el2);
    }

    private void editPilot() throws InterruptedException
    {
	getElementByLocator(By.xpath("//tr[td[div[contains(text(),'UI TEST9')]] and td[div[contains(text(),'IBWW')]]]/td[1]"))
		.click();
	getElementByLocator(By.xpath("//button[contains(text(),'Edit')]")).click();
	Thread.sleep(3000);
	getElementByLocator(By.xpath("//input[@id='USE_CASE_MODE']/../img")).click();
	driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
	getElementByLocator(By.xpath("//div[text()='On' and contains(@class,'x-combo-list-item')]")).click();
	getElementByLocator(By.xpath("//button[text()='Save']")).click();

	(new WebDriverWait(driver, 10)).until((ExpectedConditions.presenceOfElementLocated(By.xpath("//button[text()='Yes']"))));

	getElementByLocator(By.xpath("//button[text()='Yes']")).click();
    }

    private void varifyAddNew() throws InterruptedException
    {
	driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
	By by = By.xpath("//tr/td/div[contains(text(),'UI TEST9')]/../../td/div[contains(text(),'IBWW')]");
	WebElement el2 = varifyGetElementByLocator(by);
	Assert.assertNotNull(el2);
    }

    private void addNew() throws InterruptedException
    {
	(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//button[text()='Add New']")));

	getElementByLocator(By.xpath("//button[text()='Add New']")).click();

	(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By
		.xpath("//input[contains(@id,'CLIENT')]/../input[2]")));

	getElementByLocator(By.xpath("//input[contains(@id,'CLIENT')]/../input[2]")).sendKeys("IBW");

	// select Client IBWW
	(new WebDriverWait(driver, 10)).until((ExpectedConditions.presenceOfElementLocated(By
		.xpath("//div[contains(text(),'IBWW')][contains(@class,'x-combo-list-item')]"))));

	getElementByLocator(By.xpath("//div[contains(text(),'IBWW')][contains(@class,'x-combo-list-item')]")).click();

	Thread.sleep(1000);

	getElementByLocator(By.xpath("//div[contains(text(),'UI TEST9')]")).click();

	getElementByLocator(By.xpath("//button[text()='>']")).click();

	getElementByLocator(By.xpath("//button[text()='Save']")).click();

	(new WebDriverWait(driver, 10)).until((ExpectedConditions.presenceOfElementLocated(By.xpath("//button[text()='Yes']"))));

	getElementByLocator(By.xpath("//button[text()='Yes']")).click();
    }

    private void openTab() throws InterruptedException
    {
	(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By
		.xpath("//button[text()='Reference Data Maintenance']")));
	getElementByLocator(By.xpath("//button[text()='Reference Data Maintenance']")).click();
	(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By
		.xpath("//span[contains(text(),'Use Case Fund Mapping')]")));

	getElementByLocator(By.xpath("//span[contains(text(),'Use Case Fund Mapping')]")).click();

	Thread.sleep(2000);
    }

    private void login() throws InterruptedException
    {
	driver.get(baseUrl + "/html/com.ssc.gce.gceui.home.GCEWorkspace/GCEWorkspace.html");
	(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[string(@id)='user']")));
	// login
	getElementByLocator(By.xpath("//input[string(@id)='user']")).clear();
	getElementByLocator(By.xpath("//input[string(@id)='user']")).sendKeys("马赛克");
	getElementByLocator(By.xpath("//input[string(@id)='password']")).clear();
	getElementByLocator(By.xpath("//input[string(@id)='password']")).sendKeys("马赛克");
	getElementByLocator(By.xpath("//button[text()='Login']")).click();
    }

    private void initWork()
    {
	Long back = jdbcTemplate.withSql(queryFirstly).queryForLong();
	if (back == null)
	{
	    jdbcTemplate.withSql(initSql9).update();
	    jdbcTemplate.withSql(initSql8).update();
	}
	LOGGER.info("Init Done!");
    }

    private void finishWork()
    {
	jdbcTemplate.withSql(deleteFundMap).update();
	jdbcTemplate.withSql(deleteUsecaseSql).update();
    }

    @After
    public void tearDown() throws Exception
    {

	driver.quit();
	String verificationErrorString = verificationErrors.toString();
	if (!"".equals(verificationErrorString))
	{
	    fail(verificationErrorString);
	}
    }

     public static WebElement varifyGetElementByLocator( By locator ) {
     driver.manage().timeouts().implicitlyWait( 2, TimeUnit.SECONDS );
     WebElement we = null;
     boolean unfound = true;
     int tries = 0;
     while ( unfound && tries < 10 ) {
     tries += 1;
     try {
     we = driver.findElement( locator );
     unfound = false; // FOUND IT
     } catch ( StaleElementReferenceException ser ) {
     unfound = true;
     LOGGER.debug(ser);
     LOGGER.debug("will try again!");
     } catch ( NoSuchElementException nse ) {
     LOGGER.debug(nse);
     LOGGER.debug("will try again!");
     unfound = true;
     } catch ( Exception e ) {
     LOGGER.error("Unknown error."+e);
     }
     }
     driver.manage().timeouts().implicitlyWait( 1, TimeUnit.SECONDS );
     return we;
     }

    public static WebElement getElementByLocator(By locator)
    {
	WebElement we = null;
	we = driver.findElement(locator);
	return we;
    }
    
    
    @Test
    public void testHome() throws Exception
    {
	login();

	LOGGER.info("login work done");
	
	WebElement we= varifyGetElementByLocator(By.xpath("//td[div[text()='In Error']]"));
	Assert.assertNotNull(we);
	LOGGER.info("TEST HOME FINISHED!");
	
	
    }
}


selenium RC demo的代码还没有全部完成
就先放一个架子上来吧
public class TestXpathBySeleniumRC
{
    Selenium selenium = null;
    @Before
    public void setup(){
	selenium = new DefaultSelenium("127.0.0.1", 4444, "*iexplore ", "https://马赛克/home.jsp");
	selenium.start();
    }
    
    @Test
    public void testLogin(){

	selenium.open("/");
	selenium.type("//input[@name='username']","马赛克");
	selenium.type("//input[@name='PASSWORD']", "马赛克");
	selenium.click("//input[@value='Submit']");
	
    }
    
    @After
    public void tearDown(){
	selenium.close();
	selenium.stop();
    }
}


关于selenium sever。
下载了jar包直接打命令就可以起了。
java -jar yourjarpath/jarName.jar

你可能感兴趣的:(selenium)