Selenium实例:AJAX自动化测试应用

  Selenium是目前非常流行的免费自动化测试框架,适用于各种WEB应用程序的自动化测试,并且支持IE、Firefox、Safari、 Chrome、Opera等多种浏览器类型。今天Sincky以实例来演示对于AJAX页面的自动化测试处理方法。

  Selenium官网:http://seleniumhq.org/

  Selenium中文论坛:http://seleniumcn.cn/

  这里Sincky以http://tsingtao.qq.com/user/list?order=1&page=1页面的投票功能为例,演示如何通过Java TestNG方式的Selenium脚本处理AJAX。

  脚本如下:

package com.testscripts;

import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import java.util.Random;

/**
 * @author 叶赫华  2010年5月
 */
public class VoteQQ extends SeleneseTestCase {

    @Test
    public void testVote() throws Exception {
    SeleniumServer seleniumserver = new SeleniumServer();
    seleniumserver.start();
    System.out.println(seleniumserver.getPort());
    Selenium selenium = new DefaultSelenium("localhost",4444,"*firefox", "http://tsingtao.qq.com");
 
    selenium.start();
    selenium.setTimeout("60000");
    selenium.open("/user/list?order=1&page=1");

    selenium.click("link=登录");
    Thread.sleep(2000);
    selenium.selectFrame("login_frame");
    selenium.type("u", "1234567890");
    selenium.type("p", "********");
    //selenium.type("verifycode", "udfz");
    selenium.click("login_button");
    selenium.click("close");
    Thread.sleep(2000);
    selenium.selectFrame("relative=up");
 
    int i, intIndividualCount, intRandNumber, intVoteCount = 10;
    intIndividualCount = selenium.getXpathCount("//html/body/div[@id='warp']/div[@class='umain']/div/div[2]/div[@class='for_div']").intValue();
    System.out.println("intIndividualCount is:" + intIndividualCount);
    Random rand = new Random();
 
    for (i = 0; i < intVoteCount; i ++){
        intRandNumber = rand.nextInt(intIndividualCount – 1);
        System.out.println("intRandNumber is:" + intRandNumber);
        String strIndividualName = selenium.getText("//html/body/div[@id='warp']/div[@class='umain']/div/div[2]/div[@class='for_div'][" + String.valueOf(intRandNumber + 1) + "]/dl/dd/p[1]");
        selenium.click("//html/body/div[@id='warp']/div[@class='umain']/div/div[2]/div[@class='for_div'][" + String.valueOf(intRandNumber + 1) + "]/dl/dd/p[3]/a[1]/img");
        selenium.selectFrame("login_frame");
        Thread.sleep(2000);
        selenium.click("close");
        System.out.println("strIndividualName is:" + strIndividualName);
        Thread.sleep(2000);
        selenium.selectFrame("relative=up");
    } 
    selenium.stop();
    seleniumserver.stop();
 }

}

Posted in 使用说明.