WebDriver应用实例(java)——操作HTML5的存储对象

        该实例的目的是能够读取HTML5的localStorage和sessionStorage,并删除存储的内容。

        具体实例代码如下:

package cn.om.TestHTML5;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

public class TestHtml5Storage {

	WebDriver driver;
	String localStoreUrl;
	String sessionStoreUrl;

	@Test
	public void testHtml5localStorage() {
		driver.get(localStoreUrl);
		JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
		// 调用JavaScript语句“return
		// localStorage.lastname”获取存储在localStorage中“lastname”的存储值
		String lastname = (String) jsExecutor.executeScript("return localStorage.lastname;");
		// 断言获取的存储值是否为“Smith”
		Assert.assertEquals("Gates", lastname);
		// 调用JavaScript语句“localStorage.clear()”清除所有存储在localStorage中的变量值
		jsExecutor.executeScript("localStorage.clear();");
	}

	@Test
	public void testHtml5sessionStorage() {
		driver.get(sessionStoreUrl);
		JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
		// 调用JavaScript语句“return
		// localStorage.lastname”获取存储在localStorage中“lastname”的存储值
		jsExecutor.executeScript("sessionStorage.setItem('lastname','Gates');");
		String lastname = (String) jsExecutor.executeScript("return sessionStorage.lastname;");
		// 断言获取的存储值是否为“Smith”
		Assert.assertEquals("Gates", lastname);
		//清除存储在sessionStorage中的“lastname”项
		jsExecutor.executeScript("sessionStorage.removeItem('lastname');");
		// 调用JavaScript语句“localStorage.clear()”清除所有存储在localStorage中的变量值
		jsExecutor.executeScript("sessionStorage.clear();");
	}

	@BeforeMethod
	public void beforeMethod() {
		System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe");
		driver = new FirefoxDriver();
		localStoreUrl = "http://www.w3school.com.cn/tiy/t.asp?f=html5_webstorage_local";
		sessionStoreUrl = "http://www.w3school.com.cn/tiy/t.asp?f=html5_webstorage_session";
	}

	@AfterMethod
	public void afterMethod() {
		driver.quit();
	}

}

你可能感兴趣的:(selenium,自动化测试,selenium学习笔记,selenium,WebDriver,自动化测试)