Selenium学习笔记

来源:互联网 发布:甲醛清除剂 知乎 编辑:程序博客网 时间:2024/05/01 08:05

其实几天前就看了一下Selenium,不过因为之前写别的东西,就拖到了今天。Selenium包括三部分,Selenium core,Selenium IDE和Selenium RC。Selenium core自然就是他的核心代码,Selenium IDE是用JavaScript写成的Firefox插件,可以录制脚本,转换成其他语言,并且回放等。但是喵喵在这里主要想说的是Selenium RC,即Selenium Remote Control,以及它和ant的集成使用。

Selenium Remote Control现在最新的是0.9.2,可以在http://www.openqa.org/selenium-rc/下载。Selenium Remote Control可以允许你使用编程语言(Java, .NET, Perl, Python, and Ruby)实现自动化web应用UI的测试,它提供了一个Selenium Server,它可以自动的start/stop/control所有支持的浏览器(Windows平台上为Internet Explorer 6.0 and 7.0, Firefox 1.5.0.8 and 2.0, Opera 8.5.4 and 9.0.2)。

Selenium Server必须跑在JRE1.5以上版本,可以通过java -version查看当前的JRE版本。

启动Selenium Server:java -jar selenium-server.jar

可以通过-interactive参数使之以interactive mode启动,当然,在此喵喵不采用这种方式,而是用java编写testcase来进行测试。

代码如下:

import com.thoughtworks.selenium.*;
import junit.framework.*;
public class GoogleTest extends TestCase {
    private Selenium browser;
    public void setUp() {
        browser = new DefaultSelenium("localhost",
            4444, "*firefox", http://www.google.com);
        browser.start();
    }
    public void testGoogle() {
        browser.open(http://www.google.com/webhp?hl=en);
        browser.type("q", "hello world");
        browser.click("btnG");
        browser.waitForPageToLoad("5000");
        assertEquals("hello world - Google Search", browser.getTitle());
    }
    public void tearDown() {
        browser.stop();
    }
}

启动Selenium Server以后,就可以运行上面的testcase了。相信大家也都看到了,这个testcase是继承了junit的testcase。所以下面要讲的用ant进行自动化的编译和测试就和前面的ant学习笔记(一)中提到的<junit>task完全一样了。

ant脚本片段如下:

<!--  编译selenium test文件 -->
<target name="compileselenium">
    <mkdir dir="${dist.selenium}"/>
    <javac destdir="${dist.selenium}" deprecation="on">
        <src path="${src.selenium}"/>
        <classpath refid="classpath"/>
        <classpath refid="proj.libs"/>
    </javac>       
</target>
<!--  运行selenium  -->
<target name="selenium" depends="compileselenium">
    <junit printsummary="yes" haltonfailure="yes">
        <classpath>
            <path refid="classpath"/>
            <pathelement location="${dist.selenium}"/>
        </classpath>
        <formatter type="plain"/>
        <test name="GoogleTest" haltonfailure="no" outfile="result"/ >
    </junit>
</target>