7.2 编写自动化测试代码
在设计文档(也就是自动化测试用例)完成后,就可以开始正式编码了。编码最好使用NUnit或JUnit等测试框架,但这里为了便于理解,依然使用之前的编码方式。
接下来将分别使用Selenium IDE、Selenium 1和Selenium 2分别实现这些功能。
7.2.1 登录功能的测试代码
根据表7-1中的测试作例,可以使用程序清单7-1至程序清单7-5的代码对登录功能进行测试。
程序清单7-1 Selenium IDE代码
程序清单7-2 Selenium 1 C#代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Selenium; using System.Threading; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { DefaultSelenium selenium = new DefaultSelenium("localhost", 4444, "*iexplore", http://www.google.com); selenium.Start(); //第1步 selenium.Open(https://passport.360buy.com/new/login.aspx); Console.WriteLine("检查是否成功进入用户登录页面:{0}", "https://passport. 360buy.com/new/login.aspx" == selenium.GetLocation()); //第2步 selenium.Click("link=找回密码"); selenium.WaitForPageToLoad("30000"); Console.WriteLine("检查页面是否跳转到http://safe.360buy.com/findPwd/index.action:{0}", "http://safe.360buy.com/findPwd/index. action" == selenium.GetLocation()); //第3步 selenium.GoBack(); Thread.Sleep(2000); selenium.Type("id=loginname", ""); selenium.Click("id=loginsubmit"); Thread.Sleep(2000); Console.WriteLine("弹出提示“请输入用户名/邮箱/已验证手机”:{0}", selenium. IsTextPresent("请输入用户名/邮箱/已验证手机")); //第4步 selenium.Type("id=loginname", "erroruser1"); selenium.Click("id=loginsubmit"); Thread.Sleep(2000); Console.WriteLine("弹出提示“请输入密码”:{0}", selenium.IsTextPresent("请输入密码")); //第5步 selenium.Type("id=loginpwd", "errorpwd1"); selenium.Click("id=loginsubmit"); Thread.Sleep(2000); Console.WriteLine("弹出提示“您输入的账户名不存在,请核对后重新输入”:{0}", selenium. IsTextPresent("您输入的账户名不存在,请核对后重新输入")); //第6步 selenium.Type("id=loginname", "注:这里输入正确的用户名"); selenium.Type("id=loginpwd", "注:这里输入正确的密码"); selenium.Click("id=loginsubmit"); selenium.WaitForPageToLoad("30000"); Thread.Sleep(2000); Console.WriteLine("成功登录并跳转到首页,操作栏上出现“您好,xxxx”字样:{0}", "您好,realzhao![退出]" == selenium.GetText("id=loginbar")); selenium.Stop(); Console.ReadKey(); } } } |