selenium-website Demo Learning-test design-optimized Automation code

Source: Internet
Author: User
Tags assert testng

Look at Selenium's website documentation, there are some small points in the automation use case design is very reliable. Learn a lot and can be used to optimize your code.

1. Test Type:

Testing Static Content

Testing Links

Function Tests

Testing Dynamic Elements

Ajax Tests

Assert vs. Verify

The difference between assert and verify: If the assert is wrong, the subsequent content will be stopped, verify if wrong, it will be recorded and then proceed with the subsequent contents.

Choosing a location strategy

1.id and name are the most efficient and fastest;

2.xpath is everything.

Wrapping Selenium Calls

Wrap up the selenium method to reduce code redundancy

---click Method

The original code:

Selenium.click (Elementlocator); Selenium.waitforpagetoload (waitperiod);

Optimized code:

/** * Clicks and Waits for page to load. * * param elementlocator * param waitperiod */public void clickandwait (String elementlocator, String waitperiod) {        sel Enium.click (elementlocator);        Selenium.waitforpagetoload (waitperiod);}

----operation element, this is actually useful, but not fully packaged:

/*** Selenium-webdriver--Clicks on an element if it is available on a page.** param Elementlocator*/PublicvoidSafeclick(StringElementlocator){WebelementWebelement=Getdriver().Findelement(By.Xxxx(Elementlocatorif (webelement != null ) {selenium. Click (webelement} else {//Using the TestNG API for logging reporter. ( "Element:" + elementlocator +  ", is not available on a page-" + getdriver (). geturl}             /span>                

  

 

' Safe Operations ' for Element presence
/** * Selenium-webdriver--Clicks on an element if it is available on a page. * * param elementlocator */public void Safeclick (String elementlocator) {        webelement webelement = Getdriver (). Findele ment (by.xxxx (elementlocator));        if (webelement! = null) {                selenium.click (webelement);        } else {                //Using The TestNG API for logging                Reporte R.log ("Element:" + Elementlocator + ", is not available on a page-"                                + getdriver (). GETURL ());}        }

  

User Interface Mapping

To summarize, a UI Map has significant advantages

  • Using a centralized location for UI objects instead of have 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");}

    Optimized for

  • 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");}

    and properties

  • Admin.username = LoginForm:tbUsernameadmin.loginbutton = LoginForm:btnLoginadmin.events.createnewevent = Adminhomeform:_activitynewadmin.events.cancel = Addediteventform:_idcanceladmin.events.viewoldevents = Adminhomeform:_activityold

    ↑ This method, generally implemented in Java, I see, is used in class, not with Prop.properties

Page Object Design Pattern

The Page Object Design Pattern provides the following advantages

1. Separating the test code and the page code, such as positioning and layout;

2. The service or operation of the page exists in a simple warehouse, not scattered in the test case;

We encourage the reader wishes to know more to search the Internet for blogs on this subject.

Before actually in some discussion inside saw the page object design pattern, but the concrete implementation, previously had done the login page a little bit, not all page application. Feel the ability to optimize the existing code.

Pre-optimization implementation:

/*** * 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 is problems with this approach.

    1. There is no separation between the test method and the AUT "s locators (IDs in this example); Both is 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.
    2. The id-locators would is spread in multiple tests, with all tests that had to use this login page.

e.g

Optimized code: Turns the page into an object, the action belongs to the page's

/** * page Object encapsulates the sign-in page. */public class Signinpage {p        Rivate Selenium Selenium;                Public Signinpage (Selenium Selenium) {this.selenium = Selenium;  if (!selenium.gettitle (). Equals ("Sign In Page")) {throw new illegalstateexception                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 I Llegalstateexception ("This was not a Home page of logged in user, the current page" +                                        "is:" +selenium.getlocation ());                }        }        Public homepage Manageprofile () {                //Page encapsulation to manage Profile functionality                return new homepage (Selen ium);        }        /*more methods offering the services represented by Home Page of        logged User. These methods in turn might return + Page Objects for        example click on Compose Mail button could return Composemai L Class object*/}

Case:

/*** * Tests Login feature */public class Testlogin {public        void Testlogin () {                signinpage signinpage = new SignIn Page (selenium);                Homepage homepage = signinpage.loginvaliduser ("UserName", "password");                Assert.asserttrue (Selenium.iselementpresent ("Compose button"),                                "Login was unsuccessful");}        }

  

The above code should be SELENIUMRC? Not the latest implementation of selenium3.0.

A few basic rules:

1.Page objects themselves should never make verifications or assertions.

The Page object does not make a checksum assertion. The checksum assertion belongs to the test case and must be implemented in the test code, not in the Page object. Page objects contain only page representations, and methods that serve pages, regardless of the code to be tested.

2.There is one, single, verification which can, and should, being within the Page object and that are to verify the page, and possibly critical elements on the page, were loaded correctly.

There is only one page element that can be correctly positioned, which can be used to verify this page in the Page object.

The method described here is actually not very understanding, need to look at other introduction.

selenium-website Demo Learning-test design-optimized Automation code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.