自动化测试实施过程中,有测试需求:第一个用例时登录用例,只要登录成功,后面的用例就不需要重复登录。随机想到了每次请求目标网站,携带上次登录成功后服务端返回的cookie,来实现绕过登录:
保持cookie的工具类:
package ec.qa.autotest.ui.utility; import org.openqa.selenium.Cookie; /** * @author xin.wang * 保存登录后返回的COOKIE */ public class CookiesUtil { private static Cookie ck = null; public static Cookie getCk() { return ck; } public static void setCk(Cookie ck) { CookiesUtil.ck = ck; } }
@Test(groups = { "login" }, invocationCount = 1) public void loginSupplierPortal() throws InterruptedException { indexPage.clickLoginLink(); loginPage.loginPortal(info); Assert.assertEquals(loginSuccessPage.getEmailInfo(), email); CookiesUtil.setCk(WebDriverUtil.getWebDriverInstance().manage().getCookieNamed("_s_u_i_d")); System.out.println("======验证信息:" + loginSuccessPage.getEmailInfo() + "==========="); } }
if (CookiesUtil.getCk() != null) { webDriver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS); try { webDriver.get(website); } catch (Exception e) { } webDriver.manage().addCookie(CookiesUtil.getCk()); } try { webDriver.get(website); } catch (Exception e) { } webDriver.manage().timeouts().pageLoadTimeout(-1, TimeUnit.SECONDS); }
testng配置文件配置依赖登录用例:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name="EC_UI_Auto_TestSuite" verbose="3"> <!-- <listeners> <listener class-name="ec.qa.autotest.ui.testng.listener.TestngRetryListener" /> </listeners> --> <test name="SupplierPortalTest" preserve-order="true"> <groups> <dependencies> <group name="LoginPageCase" depends-on="login" /> </dependencies> </groups> <classes> <class name="ec.qa.autotest.ui.supplier.portal.testcases.IndexPageCase" /> <class name="ec.qa.autotest.ui.supplier.portal.testcases.ProductPageCase" /> </classes> </test> </suite>
运行测试用例集,只要登录用例运行成功,后面的用例会自动登录到登录后的页面.