namespace SeleniumTests { [TestFixture] public class Login { private IWebDriver driver; private StringBuilder verificationErrors; private string baseURL; private bool acceptNextAlert = true; [SetUp] public void SetupTest() { driver = new FirefoxDriver(); baseURL = "URL"; verificationErrors = new StringBuilder(); } [TearDown] public void TeardownTest() { try { driver.Quit(); } catch (Exception) { // Ignore errors if unable to close the browser } Assert.AreEqual("", verificationErrors.ToString()); } [Test] public void TheLoginTest() { driver.Navigate().GoToUrl(baseURL + "/login"); driver.FindElement(By.Name("username")).Clear(); driver.FindElement(By.Name("username")).SendKeys("USERNAME"); driver.FindElement(By.Name("password")).Clear(); driver.FindElement(By.Name("password")).SendKeys("PASSWORD"); driver.FindElement(By.XPath("//button[@type='submit']")).Click(); } } }
上面是用selenium ide 录制的某个页面的登录操作代码。像是输入用户名和密码的代码就有点重复多余繁琐,那就可以封装一个叫SendKeys的方法(包括clear和sendkeys的动作),而不需要每次去找这个element,先clear,然后再重复去找这个element再sendkeys。类似这种常用的操作都可以封装起来,放在一个Common类里(Common项目)而一些操作case放在另外的项目中。下面就是对上述例子进行封装操作。
namespace TestSelenium.Test { [TestFixture] class Test { TestSelenium.Common.Common Testcorde = new Common.Common(); [SetUp] public void Setup() { Testcorde.SetupTest(); } [TearDown] public void TearDown() { Testcorde.TeardownTest(); } [Test] public void Test01() { Testcorde.TheLoginTest("URL","USERNAME","PASSWORD" ); } } }
上面Test01就是登录操作的case,TheLoginTest(string baseurl, string username, string password)就是整个登录操作的方法。像是SetupTest、TeardownTest、SendKeys、Click、TheLoginTest都放在下面的Common类下。
namespace TestSelenium.Common { public class Common { public IWebDriver driver; public void SetupTest() { driver = new InternetExplorerDriver(@"C:/AUTO"); driver.Manage().Window.Maximize(); } public void TeardownTest() { driver.Quit(); } public void SendKeys(By by, string Message) { driver.FindElement(by).Clear(); driver.FindElement(by).SendKeys(Message); } public void Click(By by) { driver.FindElement(by).Click(); } public void TheLoginTest(string baseurl, string username, string password) { driver.Navigate().GoToUrl(baseurl + "/login"); SendKeys(By.Name("username"),username); SendKeys(By.Name("password"), password); Click(By.XPath("//button[@type='submit']")); } } }
ps.Common项目为类库输出类型,case项目需要引用Common项目并且保持都是ANYCPU生成。
转载于:https://blog.51cto.com/chenxai/1767936