Showing posts with label learn Selenium WebDriver. Show all posts
Showing posts with label learn Selenium WebDriver. Show all posts

How to Learn Selenium WebDriver in 3 Days

or How to Learn Selenium WebDriver like a JEDI


I like Star Wars movies.

I still remember seeing the first episode, A New Hope, at the cinema, back in the 1980s.

Since then, I watched it and the following 5 episodes, produced by LucasFilm, many, many times.

The new ones, produced by Disney, are still good (much simpler though) especially Rogue One and The Last Jedi.





There is an interesting difference between the old Star Wars movies and the recent ones.

In The Last Jedi, Luke Skywalker agrees to teach Rey just 3 lessons about the force. She needs to learn how to be a JEDI to be able to fight the imperial army and yes, Kylo Ren.

The lessons happen fast and only bits of knowledge and wisdom go from the teacher to the student. Not much skills as Luke is now a wise old man instead of a JEDI knight as before.

Just 3 lessons are enough for Rey to discover her potential and the mighty force. Having the force, she lifts a huge pile of rocks that stops her friends from running from the imperial army.

Unfortunately, as the episode title explains, the last JEDI disappears so in the future, there are no more JEDIs to teach about the force.

No more lessons about the force but probably the lessons are not needed any longer.

If Rey can learn the force in 3 lessons, maybe she can explain it to others in 1 lesson or maybe in just a few sentences.

The force is no longer accessible to a few but to all.
You just need to put your mind to it and there it is.


Now, why shouldnt we be able to do the same with Selenium WebDriver?

3 lessons.

It is not that hard.

The secret of the force is in how the study material is broken down per day.

Day 1
learn about html, xpath, css, browser dom, eclipse, java basics, unit testing.

Day 2
learn about object oriented notions like classes, objects, inheritance, composition, interfaces, polymorphism, generics, predicates, reflection, streams.

Day 3
learn the page object model, page factory, loadable component, slow loadable component and a few other design patterns.


And that's it, we are there, we can lift our own automation rocks.

This is totally doable if you are a Star Wars believer.

Everyone can do whatever they put their mind to.
Everything is easy to do and learn.
Everything is accessible to all of us, even the force.
The JEDI knights go away and who need them anyways?


Now, the old Star Wars episodes are a little different from the new ones.

In The Phantom Menace and Attack Of The Clones, the process of becoming a JEDI knight is explained in detail. You had to start your training at the JEDI Academy at a young age and complete it.



Then, a mentor would guide you through real life experiences until you are ready to pass the JEDI trials for becoming a knight.

No one became a JEDI in 3 lessons or 6 or 15.
No matter how skilled, talented or gifted.

Instead, the trainee would go through a long, difficult and intensive education with both teachers, peers and mentors.

This would totally work for Selenium WebDriver as well.

Selenium WebDriver learning is basically learning how to code which is best done with teachers, peers and mentors.

So Star Wars is a viable source of inspiration.

You just have to watch the proper episodes.

Watch The Last Jedi and believe that 3 lessons are sufficient.

Watch The Phantom Menace and understand that 6 months is a better time range.



SeleniumJava.com post - How to deal with windows authentication popups

If you dont like Bugs Bunny, maybe you should not continue reading.

What is the first thing that I do every morning at work?
Check the results of the automation scripts executed in Jenkins over night.
I want to know how many scripts passed or failed because of the work done in the previous day.
Most days, some scripts pass and some fail.
But recently, most scripts failed.
This was very unusual so I looked into it right away.
All failures followed the same pattern: the scripts failed on opening the site in the browser.



Where can I find a full test automation project with Selenium WebDriver?

You have been learning test automation with Selenium.

You went through lots of concepts and would like to see how they all work together.

Where can you find a project that uses everything you learned and more?

Here :)

What follows is a small project that I built a while ago for a job interview.

It uses many test automation concepts such as:
  • page factory
  • base classes
  • html classes
  • test listeners
  • test ng assertions and fixtures
  • annotations
  • custom locators (javascript and jquery)
  • screenshots
  • saving errors in text files


The exercise consisted in automating the following test case with Java and Selenium WebDriver:

  • Launch bestbuy url (www.bestbuy.ca)
  • Search a product and add it to cart
  • Go all the way through checkout process and place the order with invalid credit card
  • Capture the error message due to invalid credit card


Before downloading the project and checking the source code, a few details about the project.

Project details

Maven project
- all dependencies are managed through the pom.xml file

Test NG
- unit testing library

Java JDK 8
- used for lambda expressions and streams

Page Factory
- pattern for creating page object and page fragment classes
- the elements of page object/fragment classes have names and locators
- names and locators are implemented using annotations
- available locator types are id, xpath, css, name and javascript
  
   @Name("SEARCH_HEADER")
   @FindBy(className = "main-navigation-container") 
   public class SearchHeader extends HtmlElement{ 
 
   @Name("SEARCH_FIELD")
   @FindBy(id = "ctl00_MasterHeader_ctl00_uchead_GlobalSearchUC_TxtSearchKeyword") 
   private TextInput searchKeywordTxt;
 
   @Name("SEARCH_BUTTON")
   @FindBy(id = "ctl00_MasterHeader_ctl00_uchead_GlobalSearchUC_BtnSubmitSearch")
   private Button searchBtn; 
     
   public void search(String keyword) {
     searchKeywordTxt.click();  
     searchKeywordTxt.clear();
     searchKeywordTxt.sendKeys(keyword);
     searchBtn.click();  
   }
}


The project has the automation framework classes in the main folder and all test items in the test folder.

Main folder (framework classes)

annotations classes
- FindBy
- FindByJQUERY
- FindByJS
- Name
- Timeout
 
 package com.bestbuy.demo.annotations;

 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;

 @Retention(RetentionPolicy.RUNTIME)
 @Target({ElementType.TYPE, ElementType.FIELD})
 public @interface Name {
   String value();
 }

html element classes
 
    package com.bestbuy.demo.element;

    import org.openqa.selenium.By;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.WebElement;

    public class CheckBox extends TypifiedElement {
   
      public CheckBox(WebElement wrappedElement) {
        super(wrappedElement);
      }

      public WebElement getLabel() {
        try {
            return getWrappedElement().findElement(By.xpath("following-sibling::label"));
        } catch (NoSuchElementException e) {
            return null;
        }
      }

      public String getLabelText() {
        WebElement label = getLabel();
        return label == null ? null : label.getText();
      }

      public String getText() {
        return getLabelText();
      }

      public void select() {
        if (!isSelected()) 
            getWrappedElement().click();        
      }

      public void deselect() {
        if (isSelected()) 
            getWrappedElement().click();
      }

      public void set(boolean value) {
        if (value) 
           select();
        else 
           deselect();
      }
   }

  
exceptions classes

decorator and proxy classes used by the page factory

page class
- used as base class for the page object classes

page factory classes

miscellaneous classes such as
- custom driver class, screenshot class
- enumerations (used to avoid hardcoding data in the page objects)
- simple logger class
- property class
- TextFile class

Test folder (test items)

  • base test class (used as base by the test classes)

  • page objects classes (all page object and page fragment classes)

  • test listeners (class for taking a screenshot and logging exceptions in case of failures)
  •  
     package com.bestbuy.demotests.testlisteners;
    
     import java.lang.reflect.Field;
     import org.testng.ITestContext;
     import org.testng.ITestListener;
     import org.testng.ITestResult;
     import com.bestbuy.demo.exceptions.HtmlElementsException;
     import com.bestbuy.demo.utils.Driver.BrowserDriver;
     import com.bestbuy.demo.utils.Driver.Screenshot;
     import org.openqa.selenium.WebDriver;
     import static com.bestbuy.demotests.BaseTest.BaseTestClass.*;
    
     public class TestListener implements ITestListener {   
       
        @Override
        public void onTestFailure(ITestResult result) {       
           try {
             Screenshot screenshot = 
             new Screenshot(getDriverFromBaseTest(result));
       
             screenshot.capture(result.getName());
           } 
           catch (Exception ex) {
             throw new HtmlElementsException(ex.getMessage());
           }                 
       }  
    
       @SuppressWarnings("unchecked")
       private WebDriver getDriverFromBaseTest(ITestResult result) 
           throws IllegalAccessException {
       
          WebDriver driver = null;
       
          try { 
             Class< ? extends ITestResult> testClass = 
             (Class< ? extends ITestResult>) result.getInstance().getClass();
      
             Class< ?extends ITestResult> baseTestClass = 
             (Class< ? extends ITestResult>) testClass.getSuperclass();
      
             Field driverField = baseTestClass.getDeclaredField("driver");
        
             driver = (BrowserDriver)driverField.get(result.getInstance()); 
        
             return driver;
         } 
         catch (SecurityException | NoSuchFieldException | IllegalArgumentException ex) {     
             throw new HtmlElementsException("error getting the driver from base test");    
         }         
       
       }
        
       @Override
       public void onTestSuccess(ITestResult result) 
       {}  
      
       @Override
       public void onTestSkipped(ITestResult result) 
       {} 
      
       @Override
       public void onTestFailedButWithinSuccessPercentage(ITestResult result) 
       {} 
      
       @Override
       public void onStart(ITestContext context)     
       {} 
      
       @Override 
       public void onFinish(ITestContext context)    
       {}
      
       @Override
       public void onTestStart(ITestResult arg0)
       {}
        
     }
    
  • test class


Most interactions with web elements are done through the page factory classes.

Occasionally, Javascript code is used when buttons cannot be clicked through the page factory.

Some of the pages have random popups that are closed if displayed.

The test script does the following:
  1. Open the home page
  2. Execute a keyword search
  3. Select the Online Only filter
  4. Select a product with online availability
  5. Add the product to the cart
  6. Continue checkout on the basket page
  7. Select New Member
  8. Fill in the Ship To info
  9. Select credit card as payment method
  10. Fill in the payment info
  11. Submits transaction
  12. Verify that there is at least an error message
  13. Saves the error messages and the search keyword to a text file


The test script uses a keyword parameter which can take multiple values.


Download source code

Interested in learning how to build a project like this one?

Get started here


Best Resource for Improving Selenium Skills? Selenium code

You learned Selenium and Java test automation basics from a book, online course or youtube. 

Page object model is understood, locators are clear, explicit waits and expected conditions are straightforward.

Java concepts such as classes, objects, inheritance, looping, arrays, lists are all covered.

With the new skills, you can write test automation scripts for a variety of websites.

You are wondering now about the next level of test automation.

There is always a next level so what is it for you?

How do you go to it?

What resource should you use for guidance?





Most available books and courses target the beginner and intermediate test automation levels.

There are not many resources available on advanced test automation skills.

There is one place however, often forgotten, that has everything you need in your quest to more knowledge.

The Selenium source code.

It is extremely helpful not only to learn how to use Selenium but also to read the source code.

Doing this provides many benefits such as:

1. it shows how Selenium classes and methods work

For example, how does Selenium find a web element using the findElement() method?
How does Selenium locate an element by css locator?

2. you can learn how a framework is built

Selenium is a framework.

You can learn many things about building an automation framework from studying how the Selenium framework is built.

3. you can learn what good programming is

Selenium was created by professional developers.

What better source of learning than the code that they wrote?

4. you find out what you dont know yet but should know

For example, by reading the Page Factory code, you will learn about annotations.

And reflection.

And design patterns.

And proxy classes.

And generics.

And interfaces.

You will need all these Java concepts (and more) to make the transition to the next test automation level.

So attach the Selenium source code to the project in Eclipse and start reading.




When do you need these new skills?

Lets say that you want to have in your automation project the ability of taking screenshots automatically when an exception happens in a test script.

You use TestNG as the unit testing framework.

TestNG listeners can help but there is a problem.

You need in the test listener the driver object created in the test class or the base test class.

To get this driver object, you will use reflection and generics. 

Another example of using the new skills is creating new locator types.

Selenium provides by default a variety of locator types such as id, class, name, xpath, css.

How about using also Jquery and Javascript locators?

You will need annotations for this.


How to interact with sliders in Selenium WebDriver



Sliders allow users to select a value by dragging and dropping a handle. 

This value can be a price, a quantity, a year. 

The web page could use a textbox for getting the same information from users. 

But with sliders, the page becomes much more interesting.

Read the full article on seleniumjava.com.