本例中用百度的搜索为例,将百度首页定义成一个待测试类 HomePage
public class HomePage {private WebDriver driver;@FindBy(how = How.NAME, using = "wd")public static WebElement serchInputbox;@FindBy(how = How.ID, using = "su")public static WebElement serchBtn;@FindBy(how = How.ID, using = "container")public static WebElement serchResult;public HomePage(WebDriver driver) { this.driver = driver; ElementLocatorFactory finder = new AjaxElementLocatorFactory(driver, 120); PageFactory.initElements(finder, this);}public void enterSerchTxt(String serchTxt) { serchInputbox.clear(); serchInputbox.sendKeys(serchTxt);}public void clickSerchButton() { serchBtn.click();}public void checkResult() { assertEquals(serchResult.isDisplayed(), true);}}
上面的构造函数中用到了 PageFactory 这个三方类,另外定义了一些待测方法(测试用例中的小步骤)
下面是对应于 HomePage 的测试类 homepageTest ,您可以在HomePage上右击新建 junit file ,选择 BeforeClass, Setup ...需要注意的是命名必须是以 Test 结尾。public class homepageTest {protected static WebDriver driver;@BeforeClasspublic static void beforeClass() throws Exception { driver = new InternetExplorerDriver();}@AfterClasspublic static void tearDownAfterClass() throws Exception { driver.quit();}@Beforepublic void setUp() throws Exception { driver.get("http://www.baidu.com");}@Afterpublic void tearDown() throws Exception {}@Testpublic void testHomepage() { HomePage homepage = new HomePage(driver); homepage.enterSerchTxt("selenium"); homepage.clickSerchButton(); // maybe the net will delay, so wait for while try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } homepage.checkResult();}}
@Test 里面便是测试用例,可以有多个 @Test。
现在就可以编译下,run as --> junit test本文采用的 iedriver ,机器是64位的,会默认启动你的64位 ie(ie8分64和32位),如果您需要启32位 ie,则需要用32位的 jar 启动 selenium sever。