您的位置:首页 > 编程语言 > Java开发

在Eclipse中使用Maven配置WebDriver+Testng(一)

2014-02-26 16:17 357 查看
建立Maven项目:有2种常见的方法,方法2的优点暂时还不是太了解,但是我看网上很多人都是用的方法2。。。

方法1:

eclipse中建立Maven项目,修改pom.xml(同方法2代码)后执行Run As: Maven install.

方法2:

1. 下载Maven并配置环境变量 (mvn 的安装见 http://maven.apache.org/download.html)
设置变量名: M2_HOME=Maven安装目录

设置path: 把%M2_HOME%\bin添加到path变量中

2. cmd命令行新建一个Maven项目

mvn archetype:generate -DgroupId=com.testM2 -DartifactId=my_testng_test -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false


下面解释一下运行的命令的含义:

创建项目 archetype:generate

设定项目代码的包名 -DgroupId

指定项目名 -DartifactId

指定生成项目所使用的类型 -DarchetypeArtifactId

是否与Maven交互,-DinteractiveMode=false, 如果不指定或者设成true在创建过程中要还要设定几个值,比如打包类型、版本号的格式等等。

3. 找到该文件夹,修改pom.xml 添加以下selenium 和 testng 依赖,删除掉默认的junit依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.testM2</groupId>
<artifactId>my_testng_test</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>my_testng_test</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.40.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.7</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>


4. 打开cmd命令窗口,切换到my_testng_test文件夹,敲入命令:mvn eclipse:eclipse 回车出现Build Success信息,则创建Webdriver项目成功。


5. 在eclipse中导入所建文件夹




6. 在my_testng_test项目下新建Source Folder - src, 新建package - org.openqa.selenium.example并在package “org.openqa.selenium.example”下新建Class (修改使用Selenium官网上的例子)

package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium2Example  {
public static void main(String[] args) {
System.setProperty("webdriver.firefox.bin", "D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();

driver.get("http://www.baidu.com");

WebElement element = driver.findElement(By.name("wd"));

element.sendKeys("Cheese!");

element.submit();

System.out.println("Page title is: " + driver.getTitle());

(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});

System.out.println("Page title is: " + driver.getTitle());

driver.quit();
}
}
运行即可。

参考selenium官网上的maven说明 http://docs.seleniumhq.org/download/maven.jsp.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: