selenium-Webサイトdemoラーニング-test Design-自動化コードの最適化

11351 ワード

seleniumのウェブサイトのドキュメントを見て、中の自動化の例の設計はいくつかの小さな点が頼りになります.多くのことを学んで、自分のコードを最適化することができます.
1.テストの種類:
Testing Static Content
Testing Links
Function Tests
Testing Dynamic Elements
Ajax Tests
 

Assert vs. Verify


assertとverifyの違い:assertはwrongの場合、後の内容の実行を停止します.verify wrongの場合、記録され、後続の内容が実行されます.

Choosing a Location Strategy


  1.idとnameは最も効率的で速度が最も速い.
  2.xpathは万能です

Wrapping Selenium Calls


seleniumの方法を包装して、コードの冗長性を減らします
---clickメソッド
元のコード:
selenium.click(elementLocator);
selenium.waitForPageToLoad(waitPeriod);

最適化されたコード:
/**
 * Clicks and Waits for page to load.
 *
 * param elementLocator
 * param waitPeriod
 */
public void clickAndWait(String elementLocator, String waitPeriod) {
        selenium.click(elementLocator);
        selenium.waitForPageToLoad(waitPeriod);
}

----操作要素、これは実際に使ったことがありますが、全面的に包装されていません.
/**
 * Selenium-WebDriver -- Clicks on an element only if it is available on a page.
 *
 * param elementLocator
 */
public void safeClick(String elementLocator) { WebElement webElement = getDriver().findElement(By.XXXX(elementLocator)); if(webElement != null) { selenium.click(webElement); } else { // Using the TestNG API for logging Reporter.log("Element: " + elementLocator + ", is not available on a page - " + getDriver().getUrl()); } }

  
 

‘Safe Operations’ for Element Presence

/**
 * Selenium-WebDriver -- Clicks on an element only if it is available on a page.
 *
 * param elementLocator
 */
public void safeClick(String elementLocator) {
        WebElement webElement = getDriver().findElement(By.XXXX(elementLocator));
        if(webElement != null) {
                selenium.click(webElement);
        } else {
                // Using the TestNG API for logging
                Reporter.log("Element: " + elementLocator + ", is not available on a page - "
                                + getDriver().getUrl());
        }
}

  

User Interface Mapping


To summarize, a UI Map has two significant advantages
  • Using a centralized location for UI objects instead of having them scattered throughout the script. This makes script maintenance more efficient.
  • Cryptic HTML Identifiers and names can be given more human-readable names improving the readability of test scripts.
  • public void testNew() throws Exception {
                 selenium.open("http://www.test.com");
                 selenium.type("loginForm:tbUsername", "xxxxxxxx");
                 selenium.click("loginForm:btnLogin");
                 selenium.click("adminHomeForm:_activitynew");
                 selenium.waitForPageToLoad("30000");
                 selenium.click("addEditEventForm:_IDcancel");
                 selenium.waitForPageToLoad("30000");
                 selenium.click("adminHomeForm:_activityold");
                 selenium.waitForPageToLoad("30000");
    }
    

  • に最適化
  • public void testNew() throws Exception {
                 selenium.open("http://www.test.com");
                 selenium.type(admin.username, "xxxxxxxx");
                 selenium.click(admin.loginbutton);
                 selenium.click(admin.events.createnewevent);
                 selenium.waitForPageToLoad("30000");
                 selenium.click(admin.events.cancel);
                 selenium.waitForPageToLoad("30000");
                 selenium.click(admin.events.viewoldevents);
                 selenium.waitForPageToLoad("30000");
    }
    

    およびproperties
  • admin.username = loginForm:tbUsername
    admin.loginbutton = loginForm:btnLogin
    admin.events.createnewevent = adminHomeForm:_activitynew
    admin.events.cancel = addEditEventForm:_IDcancel
    admin.events.viewoldevents = adminHomeForm:_activityold
    

    ↑この方法は、一般的にjavaで実現されていますが、私が見たのはclassで、propではありません.properties
  •  

  • Page Object Design Pattern


    The Page Object Design Pattern provides the following advantages
    1.位置決めやレイアウトなどのテストコードとページコードを分離する.
    2.ページのサービスまたは操作を簡単な倉庫に存在させ、テスト例に散らばっているのではなく、簡単な倉庫に存在させる.
     
    We encourage the reader who wishes to know more to search the internet for blogs on this subject. 
    以前はpage objectのデザインモデルをいくつかのディスカッションで見たことがありますが、具体的には、以前ログインページのほんの少しをしたことがありますが、すべてのページアプリケーションはありません.既存のコードを最適化できるような気がします.
    最適化前の実装:
    /***
     * Tests login feature
     */
    public class Login {
    
            public void testLogin() {
                    selenium.type("inputBox", "testUser");
                    selenium.type("password", "my supersecret password");
                    selenium.click("sign-in");
                    selenium.waitForPageToLoad("PageWaitPeriod");
                    Assert.assertTrue(selenium.isElementPresent("compose button"),
                                    "Login was unsuccessful");
            }
    }
    

      
    There are two problems with this approach.
  • There is no separation between the test method and the AUT’s locators (IDs in this example); both are intertwined in a single method. If the AUT’s UI changes its identifiers, layout, or how a login is input and processed, the test itself must change.
  • The ID-locators would be spread in multiple tests, in all tests that had to use this login page.

  • e.g
    最適化されたコード:pageをオブジェクトにし、操作はそのpageに属する
    /**
     * Page Object encapsulates the Sign-in page.
     */
    public class SignInPage {
    
            private Selenium selenium;
    
            public SignInPage(Selenium selenium) {
                    this.selenium = selenium;
                    if(!selenium.getTitle().equals("Sign in page")) {
                            throw new IllegalStateException("This is not sign in page, current page is: "
                                            +selenium.getLocation());
                    }
            }
    
            /**
             * Login as valid user
             *
             * @param userName
             * @param password
             * @return HomePage object
             */
            public HomePage loginValidUser(String userName, String password) {
                    selenium.type("usernamefield", userName);
                    selenium.type("passwordfield", password);
                    selenium.click("sign-in");
                    selenium.waitForPageToLoad("waitPeriod");
    
                    return new HomePage(selenium);
            }
    }
    

      
    /**
     * Page Object encapsulates the Home Page
     */
    public class HomePage {
    
            private Selenium selenium;
    
            public HomePage(Selenium selenium) {
                    if (!selenium.getTitle().equals("Home Page of logged in user")) {
                            throw new IllegalStateException("This is not Home Page of logged in user, current page" +
                                            "is: " +selenium.getLocation());
                    }
            }
    
            public HomePage manageProfile() {
                    // Page encapsulation to manage profile functionality
                    return new HomePage(selenium);
            }
    
            /*More methods offering the services represented by Home Page
            of Logged User. These methods in turn might return more Page Objects
            for example click on Compose mail button could return ComposeMail class object*/
    
    }
    

    使用例:
    /***
     * Tests login feature
     */
    public class TestLogin {
    
            public void testLogin() {
                    SignInPage signInPage = new SignInPage(selenium);
                    HomePage homePage = signInPage.loginValidUser("userName", "password");
                    Assert.assertTrue(selenium.isElementPresent("compose button"),
                                    "Login was unsuccessful");
            }
    }
    

      
    上のコードはseleniumRCですか?最新のselenium 3ではありません.0の実装.
     
    a few basic rules:
      1.Page objects themselves should never make verifications or assertions.
    ページオブジェクトは検証と断言をしません.検証と断言はテスト例に属し、ページオブジェクトではなくテストコードで実装する必要があります.ページオブジェクトには、テストするコードとは関係なく、ページ表現のみが含まれます.
      2.There is one, single, verification which can, and should, be within the page object and that is to verify that the page, and possibly critical elements on the page, were loaded correctly. 
    正しい位置に配置できる唯一のページ要素があり、ページオブジェクトでこのページを検証できます.
    ここで紹介する方法は実はよく分からないので、他の紹介をもっと見なければなりません.
     

    Data Driven Testing


    データ駆動は、同じ例で、異なるデータで複数のデータを走る.
    e.g元のコード
         @Test( priority=2)
    	 public void testGameCard(){
    		 Verify.verifyCard(" "," "," ");
    	 }
    	
    	 @Test( priority=3)
    	 public void testLoginCard(){
    		 Verify.verifyCard(" "," "," ");
    	 }
    	 @Test( priority=4)
    	 public void testLotteryCard(){
    		 Verify.verifyCard(" "," "," ");
    	 }
    

    最適化(コードの詳細が変更されているため、上記のtestメソッド体とは異なる)
    @DataProvider(name="serviceLogin")
    	public Object[][] service2Detail(){
    	    return new Object[][]{
    	    	{" "," "},
    	    	{" "," "},
    	    	{" "," "},
    	    	{" "," "},
    	    	{" ", " "},
    	    	{" "," "}, 
    	    	{" "," "},
    	    	{" "," "},
    	    	{" "," "},
    	    	{" "," "},
    	    	};
    	    }
    @Test(dataProvider="serviceLogin")
    	public void testService2(String serviceName,String clickName,String resultTitle){
    		if(!isLogin){
    			list.login("test1998","qwr1234");
    			isLogin=list.isLogin();
    		}
    		check(serviceName,resultTitle);
    	}
    

      
    転載先:https://www.cnblogs.com/zhizhiyin/p/8960919.html