Announcement

Collapse
No announcement yet.

WebDriver Notes by Mikhail

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • WebDriver Notes by Mikhail

    Session 1.
    We would need to create the test automation environment installing the following:
    Java JDK - http://www.oracle.com/technetwork/ja...s-2133151.html
    Eclipse - http://www.eclipse.org/downloads/pac...velopers/neon2
    Selenium Standalone server - http://selenium-release.storage.goog...com/index.html (version 2.53 /selenium-server-standalone-2.53.0.jar) see the steps down below
    Firefox - https://ftp.mozilla.org/pub/firefox/...0/win64/en-US/ - Windows
    Firefox - all the platforms - https://ftp.mozilla.org/pub/firefox/releases/45.0/ if you use MAC or UNIX/LINUX
    Selenium IDE - https://addons.mozilla.org/en-US/fir.../selenium-ide/ (in case you ever decide to use it)
    JUnit - Eclipse/right mouse click on project name/Properties/Java Build Path/Libraries folder/Add Library button/select JUnit/Next button (JUnit4)/Finish button/OK - JUnit now shows up under the project name in Eclipse
    Importing outside project: open an existing project in Eclipse/File-Import-General folder/select Archive File/Next button/Browse button (in From Archive File)/navigate to the ZIP file with the project to be imported / push FINISH button
    Chrome Driver - https://chromedriver.storage.googlea...tml?path=2.28/
    Junit params jar (JUnitParams-1.0.6) - http://central.maven.org/maven2/pl/p...rams-1.0.6.jar

    Applications under test:
    Orange HRM with no records in the database - http://hrm-online.portnov.com/ (get login and password from the instructor)
    Orange HRM with many record in the database - http://hrm.portnov.com/ (get login and password from the instructor)

    To create our first Java project:

    - Run Eclipse: File/New/Java Project - give name to the project & save

    - Add selenium-server-standalone-2.53.0.jar
    ---- http://docs.seleniumhq.org/download/
    ---- Go to Previous Release (on the left) and Open the 2.53 folder; download the selenium-java-2.53.0.zip file to your system
    ---- Create a dedicated folder in a conveniet location (for example C:\drivers)
    ---- Unzip the selenium-java-2.53.0.zip file into that "drivers" folder

    - Add the libraries needed
    ---- Right mouse click on the project name in Eclipse
    ---- Build Path/Configure Build path
    ---- Libraries/click "Add External Jars" button
    ---- Navigate to "drivers" folder you created for the selenium-java-2.53.0.zip file
    ---- select both selenium-java jar files (there are only 2 files there) and push the "Open" button
    ---- click "Add External Jars" button again, go to the "Libs" sub-folder & add all the jars in there

    Creating the test case:
    - right mouse click on src folder/select New-Class menu
    - Provide name to the test case
    - check the "public static void main" check box
    - push the "Finish" button

    Install Firebug
    - in the browser go to settings
    - Select Add-Ons
    - search for "Firebug"
    - Click "Install" button
    - See the firebug button on the Firefox toolbar

    Resources:
    http://seleniumhq.github.io/selenium/docs/api/java/
    JUnit classes - http://junit.sourceforge.net/javadoc...s-noframe.html

    Home work (preparing to Session 2)
    - interview questions in the PPT file attached
    - @home install all the things we installed in the class
    - @home create the ValidLogin project and test case
    - create 3 more automated test cases for Login
    ----- valid login/invalid password
    ----- some login input/empty password field
    ----- empty login/some password input

    Valid Login Script we created in the class:
    package Session1;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;


    public class test {


    public static void main(String[] args) {
    final String HRM_URL = "http://hrm-online.portnov.com";
    final String HRM_AFTER_LOGIN_URL = "http://hrm-online.portnov.com/symfony/web/index.php/pim/viewEmployeeList";


    WebDriver driver = new FirefoxDriver();

    driver.get(HRM_URL);
    driver.findElement(By.id("txtUsername")).sendKeys( "admin");
    driver.findElement(By.id("txtPassword")).sendKeys( "password");
    driver.findElement(By.id("btnLogin")).click();

    String url = driver.getCurrentUrl();
    if (url.equals (HRM_AFTER_LOGIN_URL)) {
    System.out.println("Passed - login successful");
    }
    else {
    System.out.println("failed - login rejected");
    }

    String welcomeWho = driver.findElement (By.id("welcome")).getText();
    if (welcomeWho.equals("Welcome Admin")) {
    System.out.println("Passed by text - login successful");
    }
    else {
    System.out.println("failed by text - login unsuccessful");
    }
    driver.close();
    }
    }
    Attached Files

  • #2
    JAVA VARIABLE NAMES
    - Variable names can't start with a number. We can have numbers elsewhere in the variable name, just not at the start.
    - Variable names can't be the same as Java keywords (reserved words)
    - No spaces in variable names. We can used the underscore character, but it's common practice to have the first word start with a lowercase letter and the second or subsequent words in uppercase: firstNumber, myFirstNumber
    - Variable names are case sensitive. So firstNumber and FirstNumber are different

    JAVA VARIABLE DECLARATION AND INITIALIZATION
    - int first_number;
    first_number = 10;
    - int first_number = 10;
    - int first_number, second_number, answer;
    - first_number = 10;
    second_number = 20;
    answer = first_number + second_number;
    - answer = first_number + second_number + 12;


    Notice: The error message is not very clear? They never are. But at least it shows where the compiler got confused.

    Comment


    • #3
      Selenium Webdriver INTERNSHIP interview questions reported by students
      1. How would you use Selenium WebDriver?
      2. Write XPath for one of the elements on the given web page
      3. List different types of web element locators
      4. How would you create an Xpath for the Google Search text field
      5. What do you know about Appium?
      6. Do you know what Selenium is? What is Selenium Grid?
      7. Could you write a loop that will return even numbers from 1-10 in any language?
      8. Swap two numbers in an array
      9. How would you count the number of letters 'l' in the text "hello world"
      10. Name a few loop types
      11. What is a constructor?
      12. How do you locate elements using WebDriver?
      13. What is the difference between an Array and ArrayList?
      14. How to define a class in OOP?
      15. Explain polymorphism
      16. Explain inheritance
      17. What is the class that Selenium WebDriver is using?
      18. If you want to print "hello world" at even numbers then how would you do it?
      19. Tell me about WebDriver, how does the Selenium WebDriver interacts with the browser?
      20. What is JUnit/TestNG?
      21. What is the difference between TestNG and JUnit?
      22. How will you work on IE and GoogleChrome in WebDriver?
      23. Define data driven framework
      Attached Files

      Comment


      • #4
        String Methods in Java
        - https://docs.oracle.com/javase/7/doc...ng/String.html
        - https://www.tutorialspoint.com/java/java_strings.htm

        String Methods

        1. char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of String.
        2. int codePointAt(int index):It is similar to the charAt method however it returns the Unicode code point value of specified index rather than the character itself.
        3. void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
        4. boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.
        5. boolean contentEquals(StringBuffer sb): It compares the string to the specified string buffer.
        6. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case insensitive comparison.
        7. int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.
        8. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case during comparison.
        9. boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the substring of input to the substring of specified string.
        10. boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variation of regionMatches method with the extra boolean argument to specify whether the comparison is case sensitive or case insensitive.
        11. boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.
        12. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes then it returns true else false.
        13. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
        14. int hashCode(): It returns the hash code of the string.
        15. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.
        16. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified fromIndex.
        17. int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
        18. int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.
        19. int indexOf(String str): This method returns the index of first occurrence of specified substring str.
        20. int lastindexOf(String str): Returns the index of last occurrence of string str.
        21. String substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the specified index.
        22. String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
        23. String concat(String str): Concatenates the specified string “str” at the end of the string.
        24. String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
        25. boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
        26. String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
        27. String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.
        28. String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.
        29. String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
        30. String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given locale.
        31. String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
        32. String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.
        33. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
        34. String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.
        35. char[] toCharArray(): Converts the string to a character array.
        36. static String copyValueOf(char[] data): It returns a string that contains the characters of the specified character array.
        37. static String copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments – initial offset of subarray and length of subarray.
        38. static String valueOf(data type): This method returns a string representation of specified data type.
        39. byte[] getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.
        40. byte[] getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.
        41. int length(): It returns the length of a String.
        42. boolean matches(String regex): It checks whether the String is matching with the specified regular expression regex.

        Comment


        • #5
          LONG ("UGLY") VERSION OF THE MULTIPLE LOGIN TESTS IN ONE CLASS (to be replaced later one with the custom methods)


          import org.openqa.selenium.By;
          import org.openqa.selenium.WebDriver;
          import org.openqa.selenium.firefox.FirefoxDriver;


          public class HRMValidLogin {


          public static void main(String[] args) throws InterruptedException {
          final String HRM_URL = "http://hrm-online.portnov.com";
          final String HRM_AFTER_LOGIN_URL = "http://hrm-online.portnov.com/symfony/web/index.php/pim/viewEmployeeList";
          final String HRM_WELCOME = "Welcome Admin";
          // run the Firefox browser
          WebDriver driver = new FirefoxDriver();
          driver.get(HRM_URL);
          driver.findElement(By.id("txtUsername")).sendKeys( "admin");
          driver.findElement(By.id("txtPassword")).sendKeys( "password");
          Thread.sleep(3000);
          driver.findElement(By.id("btnLogin")).click();

          String url = driver.getCurrentUrl(); //get the ACTUAL url
          if (url.equals (HRM_AFTER_LOGIN_URL)) {
          System.out.println("Passed - login successful");
          }
          else {
          System.out.println("Failed - login unsuccessful");
          }

          String str = driver.findElement(By.id("welcome")).getText();

          if (str.equals(HRM_WELCOME)){
          System.out.println("Login Successful!");
          }
          else{
          System.out.println("Login Failed!");
          }

          // Valid Login + Invalid password test
          driver.get(HRM_URL);
          driver.findElement(By.id("txtUsername")).sendKeys( "admin");
          driver.findElement(By.id("txtPassword")).sendKeys( "passvord");
          Thread.sleep(3000);
          driver.findElement(By.id("btnLogin")).click();


          str = driver.findElement(By.id("spanMessage")).getText() ;

          if (str.equals("Invalid Credentials")){
          System.out.println("Invalid Login Successfuly rejected!");
          }
          else{
          System.out.println("Invalid Login Message Failed!");
          }

          // Valid Login + Empty password test
          driver.get(HRM_URL);
          driver.findElement(By.id("txtUsername")).sendKeys( "admin");
          driver.findElement(By.id("txtPassword")).sendKeys( "");
          Thread.sleep(3000);
          driver.findElement(By.id("btnLogin")).click();


          str = driver.findElement(By.id("spanMessage")).getText() ;

          if (str.equals("Password cannot be empty")){
          System.out.println("Invalid Login Successfuly rejected!");
          }
          else{
          System.out.println("Invalid Login Message Failed!");
          }


          // Empty Login + Valid password test
          driver.get(HRM_URL);
          driver.findElement(By.id("txtUsername")).sendKeys( "");
          driver.findElement(By.id("txtPassword")).sendKeys( "password");
          Thread.sleep(3000);
          driver.findElement(By.id("btnLogin")).click();


          str = driver.findElement(By.id("spanMessage")).getText() ;

          if (str.equals("Username cannot be empty")){
          System.out.println("Invalid Password Successfuly rejected!");
          }
          else{
          System.out.println("Invalid Password Message Failed!");
          }
          driver.close();
          }
          }

          Comment


          • #6
            Session 2 homework:
            - Create the Login by methods test with printout of number of failures (using the counter we created); close the webdriver at the end of the script
            - Practice the "Hello world" by "l" java exapmple
            - Try to find answers to 23 interview questions, document the answers
            - Watch XPATH video with Ellie - https://www.youtube.com/watch?v=9AOCJ4Evgk0 start at 12:20 and go up to 1:17:30

            Comment


            • #7
              Hello World by "l" java script

              public class CharCounter {

              public static void main(String[] args) {
              String sample = "hello world"; //create a variable for the string to search
              String strToFind = "l"; //create variable for the letter to be counted in the string
              char chrToFind = strToFind.charAt(0); //convert string letter into char letter
              char arraysample[] = sample.toCharArray(); //create an array of letters of the hello world string
              int length = sample.length(); //find out the length of the hello world string (the array)
              int charCounter = 0; //create a variable to count encounters of "l" in the "hello world"

              for(int i = 0; i < length; i++)
              {
              if (arraysample[i] == chrToFind) {
              charCounter++;
              }
              }

              System.out.println ("There are " +charCounter+ " encounters of letter " + "\""+chrToFind+"\"" +" in the string \""+sample+"\"");

              //Another version of the code - just one line
              System.out.println(sample.split(strToFind).length-1); //create nice text yourself
              }

              }

              Comment


              • #8
                LOGIN BY METHOD

                import org.openqa.selenium.By;
                import org.openqa.selenium.WebDriver;
                import org.openqa.selenium.firefox.FirefoxDriver;


                public class CompleteLoginLong {
                public static String url = "http://hrm-online.portnov.com";
                public static String logout_url = "http://hrm-online.portnov.com/symfony/web/index.php/auth/logout";
                public static int count = 0;


                public static void main(String[] args) throws InterruptedException {
                WebDriver wd = new FirefoxDriver();


                System.out.println(login(wd, "admin", "password",
                "http://hrm-online.portnov.com/symfony/web/index.php/pim/viewEmployeeList"));


                System.out.println(login(wd, "admin", "password1", "Invalid credentials"));


                System.out.println(login(wd, "admin1", "password", "Invalid credentials"));


                System.out.println(login(wd, "admin1", "password1", "Invalid credentials"));


                System.out.println(login(wd, "admin", "", "Password cannot be empty"));


                System.out.println(login(wd, "", "password", "Username cannot be empty"));


                System.out.println(login(wd, "", "", "Username cannot be empty"));


                wd.close();


                if (count == 0)
                System.out.println("Test case passed");
                else
                System.out.println("Test case failed " + count + " times");


                }


                public static String login(WebDriver wd, String username, String password, String expected)
                throws InterruptedException {
                wd.get(url);
                wd.findElement(By.id("txtUsername")).sendKeys(user name);
                wd.findElement(By.id("txtPassword")).sendKeys(pass word);
                wd.findElement(By.id("btnLogin")).click();
                Thread.sleep(1000);
                String result;
                if (wd.getCurrentUrl().equals(expected) || wd.findElement(By.id("spanMessage")).getText().equ als(expected)) {
                wd.get(logout_url);
                return result = "Pass";
                } else {
                count++;
                return result = "Fail";
                }
                }
                }

                Comment


                • #9
                  Session 3.


                  Home Work – Interview Questions:
                  · Hello World program (how many times “l”)

                  Practicing Java/Interview Questions:
                  · Even numbers out of first 50 integers

                  Create Employee Test:
                  · Manually explain the test case
                  · Use Firebug to show – there is no locator
                  · Explain XPath
                  · Install Firepath
                  · Type in the script with explanations
                  · Go over Locators PPT

                  Find Employee Test:

                  Interview Questions:
                  · List different types of web element locators (8)
                  · How will you work on IE and Google Chrome in WebDriver?

                  Glossary:
                  · Selenium IDE
                  · DOM
                  · SWITCH
                  · WHILE loop
                  · XPATH
                  · Method

                  Resources:
                  · CSS: http://www.w3.org/TR/css3-selectors/
                  · Xpath: http://www.w3schools.com/Xpath/
                  · Xpath: http://www.w3.org/TR/xpath
                  · Webdriver Session3 PDF

                  Home work:
                  · Install Firepath
                  · Install Selenium IDE
                  Attached Files

                  Comment


                  • #10
                    import org.openqa.selenium.By;
                    import org.openqa.selenium.WebDriver;
                    import org.openqa.selenium.firefox.FirefoxDriver;


                    public class CreateEmployee {


                    public static void main(String[] args) {


                    String url = "http://hrm-online.portnov.com/symfony/web/index.php/auth/login";
                    WebDriver wd = new FirefoxDriver();
                    wd.get(url);


                    while (true) {
                    if (validlogin(wd, "admin", "password"))
                    System.out.println("Login successful");
                    else {
                    System.out.println("Login failed");
                    break;
                    }


                    wd.findElement(By.id("menu_pim_addEmployee")).clic k();


                    if (addEmployee(wd, "Test", "User"))
                    System.out.println("User added");
                    else {
                    System.out.println("User have not been added");
                    break;
                    }


                    break;
                    }


                    wd.close();


                    }


                    public static boolean validlogin(WebDriver wd, String username, String password) {
                    wd.findElement(By.id("txtUsername")).sendKeys(user name);
                    wd.findElement(By.id("txtPassword")).sendKeys(pass word);
                    wd.findElement(By.id("btnLogin")).click();
                    return wd.findElement(By.id("welcome")).isDisplayed();
                    }


                    public static boolean addEmployee(WebDriver wd, String firstName, String lastName) {
                    wd.findElement(By.id("firstName")).sendKeys(firstN ame);
                    wd.findElement(By.id("lastName")).sendKeys(lastNam e);
                    wd.findElement(By.id("btnSave")).click();
                    return wd.findElement(By.xpath("//*[@id='profile-pic']/h1")).getText().equals(firstName + " " + lastName);


                    }


                    }

                    Comment


                    • #11
                      EVEN NUMBERS



                      public class EvenNumbers {


                      public static void main(String[] args) {

                      int limit = 50;

                      for(int i=1; i <= limit; i++){
                      if( i % 2 == 0){
                      System.out.print(i + " ");
                      }
                      }
                      }


                      }

                      Comment


                      • #12
                        FIND EMPLOYEE

                        import org.openqa.selenium.By;
                        import org.openqa.selenium.NoSuchElementException;
                        import org.openqa.selenium.WebDriver;
                        import org.openqa.selenium.firefox.FirefoxDriver;


                        public class FindEmployee {


                        public static void main(String[] args) throws InterruptedException {
                        String url = "http://hrm.portnov.com";
                        String[] employees = { "johnny", "anju", "Anna", "Didi", "Kuzhali", "Sanskar", "Kam", "Keya", "Manisha",
                        "Oleg" };
                        String[] titles = { "Office Manager", "QA Lead", "QA Manager", "QA Manager", "", "tester", "", "CEO", "QA Lead",
                        "" };


                        int office = 0, lead = 0, qa = 0, tester = 0, ceo = 0, no_title = 0;


                        WebDriver wd = new FirefoxDriver();


                        wd.get(url);


                        login(wd, "sweta", "november");


                        for (int i = 0; i < employees.length; i++) {
                        switch (jobStatus(wd, employees[i])) {
                        case "Office Manager":
                        System.out.println(
                        "Current job title " + employees[i] + " is Office Manager, expected job title is " + titles[i]);
                        System.out.println(checkEmployee("Office Manager", titles[i]));
                        office++;
                        break;
                        case "QA Lead":
                        System.out.println(
                        "Current job title " + employees[i] + " is QA Lead, expected job title is " + titles[i]);
                        System.out.println(checkEmployee("QA Lead", titles[i]));
                        lead++;
                        break;
                        case "QA Manager":
                        System.out.println(
                        "Current job title " + employees[i] + " is QA Manager, expected job title is " + titles[i]);
                        System.out.println(checkEmployee("QA Manager", titles[i]));
                        qa++;
                        break;
                        case "tester":
                        System.out.println(
                        "Current job title " + employees[i] + " is Tester, expected job title is " + titles[i]);
                        System.out.println(checkEmployee("tester", titles[i]));
                        tester++;
                        break;
                        case "CEO":
                        System.out.println("Current job title " + employees[i] + " is CEO, expected job title is " + titles[i]);
                        System.out.println(checkEmployee("CEO", titles[i]));
                        ceo++;
                        break;
                        case "":
                        System.out.println("Job title " + employees[i] + " is not present");
                        System.out.println(checkEmployee("", titles[i]));
                        no_title++;
                        break;
                        case "Record is not found":
                        System.out.println(employees[i] + " is not found");
                        System.out.println("Test case failed");
                        break;
                        default:
                        System.out.println("Unexpected error");
                        break;
                        }
                        }


                        wd.close();


                        System.out.println("Office Manager - " + office);
                        System.out.println("QA Lead - " + lead);
                        System.out.println("QA Manager - " + qa);
                        System.out.println("Tester - " + tester);
                        System.out.println("CEO - " + ceo);
                        System.out.println("No job title - " + no_title);


                        }


                        public static boolean login(WebDriver wd, String username, String password) {
                        wd.findElement(By.id("txtUsername")).sendKeys(user name);
                        wd.findElement(By.id("txtPassword")).sendKeys(pass word);
                        wd.findElement(By.id("btnLogin")).click();
                        return wd.findElement(By.id("welcome")).isDisplayed();
                        }


                        public static String jobStatus(WebDriver wd, String name) throws InterruptedException {
                        wd.findElement(By.id("empsearch_employee_name_empN ame")).click();
                        wd.findElement(By.id("empsearch_employee_name_empN ame")).clear();
                        wd.findElement(By.id("empsearch_employee_name_empN ame")).sendKeys(name);
                        wd.findElement(By.id("empsearch_id")).click();
                        Thread.sleep(3000);
                        wd.findElement(By.xpath("//*[@id='searchBtn']")).click();
                        Thread.sleep(3000);
                        String jobTitle = "";
                        try {
                        jobTitle = wd.findElement(By.xpath("//*[@id='resultTable']/tbody/tr[1]/td[5]")).getText();
                        } catch (NoSuchElementException e) {
                        jobTitle = "Record is not found";
                        }
                        return jobTitle;
                        }


                        public static String checkEmployee(String currentTitle, String expectedTitle) {
                        String status;
                        if (currentTitle.equals(expectedTitle))
                        status = "Test case passed";
                        else
                        status = "Test case failed";
                        return status;
                        }
                        }

                        Comment


                        • #13
                          Page Object session (#4)
                          ===========================JUNIT================== =============
                          package PageObject_Junit;
                          import static org.junit.Assert.*;
                          import org.junit.After;
                          import org.junit.AfterClass;
                          import org.junit.Before;
                          import org.junit.BeforeClass;
                          import org.junit.Test;
                          import org.openqa.selenium.WebDriver;
                          //import org.openqa.selenium.chrome.ChromeDriver;
                          import org.openqa.selenium.firefox.FirefoxDriver;
                          import org.openqa.selenium.support.PageFactory;




                          public class Session4 {

                          public static WebDriver wd;
                          public static String URL_Login = "http://hrm.portnov.com/symfony/web/index.php/auth/login";
                          public static String URL_Logout = "http://hrm.portnov.com/symfony/web/index.php/auth/logout";
                          public static String username = "sweta";
                          public static String password = "november";

                          @BeforeClass
                          public static void setUpBeforeClass() throws Exception {

                          }

                          @AfterClass
                          public static void tearDownAfterClass() throws Exception {

                          }


                          @Before
                          public void setUp() throws Exception {
                          wd = new FirefoxDriver();
                          wd.get(URL_Login);
                          PageFactory.initElements(wd, LoginPage.class);
                          PageFactory.initElements(wd, EmployeeListPage.class);
                          Modules.login(username, password);
                          assertEquals("Welcome sweta", EmployeeListPage.welcome.getText()); //JUnit method
                          }


                          @After
                          public void tearDown() throws Exception {
                          wd.get(URL_Logout);
                          wd.close();
                          }

                          @Test
                          public void checkInfo() {
                          EmployeeListPage.viewMyDetails.click();
                          PageFactory.initElements(wd, MyInfoPage.class);
                          assertEquals("Personal Details", MyInfoPage.infoBlock.getText()); //validate the correct page is opened
                          assertEquals(username + " " + username, MyInfoPage.name.getText()); //validate full user name name on the opened page
                          }


                          @Test
                          public void addWorkEx() throws InterruptedException {
                          PageFactory.initElements(wd, MyInfoPage.UserMenu.class);
                          PageFactory.initElements(wd, MyInfoPage.UserMenu.Qualifications.class);
                          EmployeeListPage.viewMyDetails.click();
                          MyInfoPage.UserMenu.menuQualifications.click();
                          assertEquals("Work Experience", MyInfoPage.UserMenu.Qualifications.titleWorkExp.ge tText());
                          assertTrue(MyInfoPage.UserMenu.Qualifications.btnA ddWorkExp.isEnabled());
                          MyInfoPage.UserMenu.Qualifications.btnAddWorkExp.c lick();
                          MyInfoPage.UserMenu.Qualifications.txtCompany.send Keys("CISCO");
                          MyInfoPage.UserMenu.Qualifications.txtJobTitle.sen dKeys("QA");
                          MyInfoPage.UserMenu.Qualifications.btnWorkExpSave. click();
                          assertEquals("CISCO", MyInfoPage.UserMenu.Qualifications.frmCompanyName. getText());
                          assertEquals("QA", MyInfoPage.UserMenu.Qualifications.frmJobTitle.get Text());
                          }

                          @Test
                          public void delWorkEx() throws InterruptedException {
                          PageFactory.initElements(wd, MyInfoPage.UserMenu.class);
                          PageFactory.initElements(wd, MyInfoPage.UserMenu.Qualifications.class);
                          EmployeeListPage.viewMyDetails.click();
                          MyInfoPage.UserMenu.menuQualifications.click();
                          assertEquals("Work Experience", MyInfoPage.UserMenu.Qualifications.titleWorkExp.ge tText());
                          assertTrue(MyInfoPage.UserMenu.Qualifications.btnD elWorkExp.isEnabled());
                          MyInfoPage.UserMenu.Qualifications.frmCheckBox.cli ck();
                          MyInfoPage.UserMenu.Qualifications.btnDelWorkExp.c lick();
                          }


                          }
                          ========================================LOGIN PAGE=============================
                          package PageObject_Junit;


                          import org.openqa.selenium.WebDriver;
                          import org.openqa.selenium.WebElement;
                          import org.openqa.selenium.support.FindBy;
                          import org.openqa.selenium.support.How;


                          public class LoginPage {
                          public static WebDriver wd;

                          public LoginPage (WebDriver wd){ //constructor
                          LoginPage.wd = wd;
                          }

                          @FindBy(how=How.ID, using="txtUsername")
                          public static WebElement login;

                          @FindBy(how=How.ID, using="txtPassword")
                          public static WebElement password;

                          @FindBy(how=How.ID, using="btnLogin")
                          public static WebElement btnLogin;
                          }
                          =========================================EMPLOYEE LIST PAGE=============================
                          package PageObject_Junit;


                          import org.openqa.selenium.WebDriver;
                          import org.openqa.selenium.WebElement;
                          import org.openqa.selenium.support.FindBy;
                          import org.openqa.selenium.support.How;


                          public class EmployeeListPage {
                          public static WebDriver wd;

                          public EmployeeListPage (WebDriver wd){
                          LoginPage.wd = wd;
                          }

                          @FindBy(how=How.ID, using="welcome")
                          public static WebElement welcome;

                          @FindBy(how=How.ID, using="searchBtn")
                          public static WebElement searchBtn;

                          @FindBy(how=How.ID, using="resetBtn")
                          public static WebElement resetBtn;

                          @FindBy(how=How.ID, using="btnAdd")
                          public static WebElement btnAdd;

                          @FindBy(how=How.ID, using="btnDelete")
                          public static WebElement btnDelete;

                          @FindBy(how=How.ID, using="empsearch_employee_name_empName")
                          public static WebElement txtEmployeeName;

                          @FindBy(how=How.ID, using="menu_pim_viewMyDetails")
                          public static WebElement viewMyDetails;


                          }
                          ==================================MODULES========= ===========
                          package PageObject_Junit;


                          public class Modules {
                          public static void login(String username, String password){
                          LoginPage.login.sendKeys(username);
                          LoginPage.password.sendKeys(password);
                          LoginPage.btnLogin.click();
                          }
                          }
                          =====================================MY INFO PAGE========================
                          package PageObject_Junit;


                          import org.openqa.selenium.WebDriver;
                          import org.openqa.selenium.WebElement;
                          import org.openqa.selenium.support.FindBy;
                          import org.openqa.selenium.support.How;


                          public class MyInfoPage {
                          public static WebDriver wd;

                          public MyInfoPage (WebDriver wd){
                          LoginPage.wd = wd;
                          }

                          @FindBy(how=How.XPATH, using="//*[@id='profile-pic']/h1")
                          public static WebElement name;

                          @FindBy(how=How.ID, using="personal_txtEmpFirstName")
                          public static WebElement txtEmpFirstName;

                          @FindBy(how=How.ID, using="personal_txtEmpLastName")
                          public static WebElement txtEmpLastName;

                          @FindBy(how=How.XPATH, using="//*[@id='pdMainContainer']/div[1]/h1")
                          public static WebElement infoBlock;

                          public static class UserMenu {

                          @FindBy(how=How.XPATH, using="//*[@id='sidenav']/li[10]/a")
                          public static WebElement menuQualifications;


                          public static class Qualifications{

                          @FindBy(how=How.XPATH, using="//*[@id='sectionWorkExperience']/div[1]/h1")
                          public static WebElement titleWorkExp;

                          @FindBy(how=How.ID, using="addWorkExperience")
                          public static WebElement btnAddWorkExp;

                          @FindBy(how=How.ID, using="delWorkExperience")
                          public static WebElement btnDelWorkExp;

                          @FindBy(how=How.XPATH, using="//*[@id='frmDelWorkExperience']/table/tbody/tr/td[1]/input[6]")
                          public static WebElement frmCheckBox;

                          @FindBy(how=How.XPATH, using="//*[@id='frmDelWorkExperience']/table/tbody/tr/td[2]")
                          public static WebElement frmCompanyName;

                          @FindBy(how=How.XPATH, using="//*[@id='frmDelWorkExperience']/table/tbody/tr/td[3]")
                          public static WebElement frmJobTitle;

                          @FindBy(how=How.XPATH, using="//*[@id='headChangeWorkExperience']")
                          public static WebElement headChangeWorkExp;

                          @FindBy(how=How.ID, using="experience_employer")
                          public static WebElement txtCompany;

                          @FindBy(how=How.ID, using="experience_jobtitle")
                          public static WebElement txtJobTitle;

                          @FindBy(how=How.ID, using="btnWorkExpSave")
                          public static WebElement btnWorkExpSave;

                          @FindBy(how=How.ID, using="btnWorkExpCancel")
                          public static WebElement btnWorkExpCancel;

                          }
                          }
                          }
                          Attached Files

                          Comment


                          • #14
                            As a language that has the Object-Oriented feature, Java supports the following fundamental concepts:
                            - Polymorphism
                            - Inheritance
                            - Encapsulation
                            - Abstraction
                            - Classes
                            - Objects
                            - Instance
                            - Method


                            Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.


                            A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.


                            Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class. Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.


                            Creating an Object (same as Instance)
                            An object is created from a class. There are three steps when creating an object from a class:
                            - Declaration − A variable declaration with a variable name with an object type.
                            - Instantiation − The 'new' keyword is used to create the object.
                            - Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.


                            A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name.


                            Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship.


                            Encapsulation is one of the four fundamental OOP concepts along with inheritance, polymorphism, and abstraction. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.


                            To achieve encapsulation in Java:
                            - Declare the variables of a class as private.
                            - Provide public setter and getter methods to modify and view the variables values.


                            Abstraction in OOP is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.


                            Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

                            Comment


                            • #15
                              session 5 data
                              Steps of adding new files to the Session4 project:
                              Page_Object (package)/right mouse click/Import/File System/Next button/Browse button/select Session5/select Session4
                              check - addWorkEx.java
                              check - checkInfo.java
                              check - delWorkEx.java
                              check -EmployeeListpage.java
                              check - testRunner.java
                              check - TestSuite.java
                              /FINISH/YES to ALL


                              Create new Package Session5 - src/right mouse click/new/package/name=session5/Finish
                              Session5 package/right mouse click/Import/File System/Next button/Browse button/select Session5/select Session5/Select All/FINISH


                              Add JUnitParams-1.0.6 to the project:
                              PROJECT NAME - right mouse click/Java Build Path/Libraries folder/Add External JARS button/navigate to JUnitParams-1.0.6/select/open/OK


                              PageObj.java - testing links on https://www.portnov.com/resources/software-qa-links using PageFactory
                              Links.java - Page Object of the https://www.portnov.com/resources/software-qa-links page
                              FindElements.java - testing links without Page Objects
                              AddEmployeeCsv.java - Adding an employee in HRM from CSV file

                              Attached Files

                              Comment

                              Working...
                              X