代码改变世界

使用开源工具SeleniumRC进行功能测试

2010-03-01 14:39  杨延成  阅读(1751)  评论(2编辑  收藏  举报

什么是 Selenium?

Selenium 是 ThoughtWorks 专门为 Web 应用程序编写的一个验收测试工具。据 Selenium 主页所说,与其他测试工具相比,使用 Selenium 的最大好处是:

Selenium 测试直接在浏览器中运行,就像真实用户所做的一样。Selenium 测试可以在 Windows、Linux 和 MacintoshAnd 上的 Internet Explorer、Mozilla 和 Firefox 中运行。其他测试工具都不能覆盖如此多的平台。

使用 Selenium 和在浏览器中运行测试还有很多其他好处。下面是主要的两大好处:

  • 通过编写模仿用户操作的 Selenium 测试脚本,可以从终端用户的角度来测试应用程序。
  • 通过在不同浏览器中运行测试,更容易发现浏览器的不兼容性。

Selenium 的核心,也称 browser bot,是用 JavaScript 编写的。这使得测试脚本可以在受支持的浏览器中运行。browser bot 负责执行从测试脚本接收到的命令,测试脚本要么是用 HTML 的表布局编写的,要么是使用一种受支持的编程语言编写的。

在下面的情况下,可以选择SeleniumRC进行功能测试。

  • condition statements
  • iteration
  • logging and reporting of test results
  • error handling, particularly unexpected errors
  • database testing
  • test case grouping
  • re-execution of failed tests
  • test case dependency
  • screenshot capture of test failures

首先要下载SeleniumRC,不用安装,解压即可,可以看到这样几个目录,下图示:

selenium-server-1.0.1目录,是服务器端,他可以接受测试程序指令,并将测试结果返回测试程序。
在测试前必须先启动他,启动过程:开始-运行-cmd-cd <服务器端目录>-java -jar selenium-server.jar
(服务器端其实就是个Jar文件)

 

然后就可以进行客户端,本文用C#来进行测试,首先建立一个C#类库工程,添加引用selenium-dotnet-client-driver-1.0.1目录下的所有DLL,具体如下图示。

下面,新建类SeleniumTest,具体代码如下:

 

代码
1 [TestFixture]
2 public class SeleniumTest
3 {
4 private ISelenium selenium;
5 private StringBuilder verificationErrors;
6
7 [SetUp]
8 public void SetupTest()
9 {
10 selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://localhost:2896/WebTestSite/");
11 selenium.Start();
12
13 verificationErrors = new StringBuilder();
14 }
15
16 [TearDown]
17 public void TeardownTest()
18 {
19 try
20 {
21 selenium.Stop();
22 }
23 catch (Exception)
24 {
25 // Ignore errors if unable to close the browser
26   }
27 Assert.AreEqual("", verificationErrors.ToString());
28 }
29
30 [Test]
31 public void TheSeleniumTest()
32 {
33 selenium.Open("/WebTestSite/");
34 selenium.Type("TextBox1", "qeq");
35 selenium.Type("TextBox2", "qwe");
36 selenium.Click("Button1");
37
38 //判断是否出现alert("fail")
39   Assert.AreEqual("fail", selenium.GetAlert());
40
41 selenium.Type("TextBox1", "123");
42 selenium.Type("TextBox2", "123");
43 selenium.Click("Button1");
44 Assert.AreEqual("fail", selenium.GetAlert());
45
46 //点击链接
47   selenium.Click("link=2");
48 //等待
49   selenium.WaitForPageToLoad("30000");
50 selenium.Click("link=3");
51 selenium.WaitForPageToLoad("30000");
52
53 }
54 [Test]
55 public void TestTitle()
56 {
57 selenium.Open("/WebTestSite/**.aspx");
58 Assert.AreEqual("yourtitle", selenium.GetTitle());
59
60 }
61 }

 

这样,就建好了,可以打开NUit进行测试,也可以直接写个main进行测试。

 

seleniumhq官方文档:
http://seleniumhq.org/docs/05_selenium_rc.html#introduction

 

参考:

用 Selenium 自动化验收测试

seleniumhq官网