Practice.cybertekschool.com



selenium topics and test casesTable of Contents TOC \o "1-3" \h \z \u basic navigation PAGEREF _Toc9404614 \h 1Test cases PAGEREF _Toc9404615 \h 1open browser, get page, get title PAGEREF _Toc9404616 \h 1Open browser, get page, get URL PAGEREF _Toc9404617 \h 1CODE EXAMPLE PAGEREF _Toc9404618 \h 1get page, get title PAGEREF _Toc9404619 \h 1get, navigate to, back, forward, refresh PAGEREF _Toc9404620 \h 2navigate to, back, forward PAGEREF _Toc9404621 \h 3get url PAGEREF _Toc9404622 \h 3Basic locators, web element class PAGEREF _Toc9404623 \h 4Test cases PAGEREF _Toc9404624 \h 4Basic authentication Address book PAGEREF _Toc9404625 \h 4Basic authentication Zero bank PAGEREF _Toc9404626 \h 4Search Amazon PAGEREF _Toc9404627 \h 5Retrieve password PAGEREF _Toc9404628 \h 5Click on links PAGEREF _Toc9404629 \h 5CODE EXAMPLE PAGEREF _Toc9404630 \h 5maximize browser, id, name, class name, sendkeys, click PAGEREF _Toc9404631 \h 5implicit wait vs thread.sleep, tagname, sendkeys PAGEREF _Toc9404632 \h 7id, name, linktext, partial linktext, sendkeys, click PAGEREF _Toc9404633 \h 8tagname PAGEREF _Toc9404634 \h 8handling different elements,: input, checkbox, radiobutton, dropdown; xpath PAGEREF _Toc9404635 \h 9Test cases PAGEREF _Toc9404636 \h 9Verify checkbox functionality PAGEREF _Toc9404637 \h 9Mercury Tours radio button functionality PAGEREF _Toc9404638 \h 9Mercury Tours departure list PAGEREF _Toc9404639 \h 9input box PAGEREF _Toc9404640 \h 10input PAGEREF _Toc9404641 \h 11input PAGEREF _Toc9404642 \h 11dropdown PAGEREF _Toc9404643 \h 12radio buttons PAGEREF _Toc9404644 \h 13Checkboxes PAGEREF _Toc9404645 \h 14TestNG Intro PAGEREF _Toc9404646 \h 15Assertions PAGEREF _Toc9404647 \h 15@beforemethod @aftermethod PAGEREF _Toc9404648 \h 16beforemethod vs before class PAGEREF _Toc9404649 \h 17after method vs after class PAGEREF _Toc9404650 \h 17mixed annotations PAGEREF _Toc9404651 \h 18testng order, depends on PAGEREF _Toc9404652 \h 19depends on PAGEREF _Toc9404653 \h 19Mixed dependencies PAGEREF _Toc9404654 \h 20more dependencies PAGEREF _Toc9404655 \h 20priority, test that fails PAGEREF _Toc9404656 \h 21Tabs, frames, alerts PAGEREF _Toc9404657 \h 23LINKS PAGEREF _Toc9404658 \h 24pop up PAGEREF _Toc9404659 \h 24Iframe PAGEREF _Toc9404660 \h 25Iframe switch options PAGEREF _Toc9404661 \h 26Javascript alerts PAGEREF _Toc9404662 \h 31Switch tabs PAGEREF _Toc9404663 \h 32HOMEWORK PAGEREF _Toc9404664 \h 35SOFT ASSERTIONS, TEST BASE, ACTIONS, FILE DOWNLOAD PAGEREF _Toc9404665 \h 35Test base PAGEREF _Toc9404666 \h 35Actions double click PAGEREF _Toc9404667 \h 36Actions drag and drop PAGEREF _Toc9404668 \h 37Actions hover PAGEREF _Toc9404669 \h 38Verify file exists PAGEREF _Toc9404670 \h 39Test that extends test base PAGEREF _Toc9404671 \h 39Soft assert 1 PAGEREF _Toc9404672 \h 40Soft assert 2 PAGEREF _Toc9404673 \h 40HOMEWORK PAGEREF _Toc9404674 \h 42FILE UPLOAD. WEB TABLES PAGEREF _Toc9404675 \h 42Table: select whole table, select column names, select certain row, select by coordinate, select row, table size, index PAGEREF _Toc9404676 \h 42Xpath: index, parent PAGEREF _Toc9404677 \h 42HOMEWORK PAGEREF _Toc9404678 \h 48EXCEPTIONS REVIEW, VERIFY ELEMENT EXISTS PAGEREF _Toc9404679 \h 49Negative verifications Verify element does NOT exist PAGEREF _Toc9404680 \h 49PAGE OBJECT MODEL PAGEREF _Toc9404681 \h 51Test Cases PAGEREF _Toc9404682 \h 51Wrong password PAGEREF _Toc9404683 \h 51No username PAGEREF _Toc9404684 \h 51No password PAGEREF _Toc9404685 \h 51CODE EXAMPLE PAGEREF _Toc9404686 \h 51Driver class PAGEREF _Toc9404687 \h 51Test Base using driver class PAGEREF _Toc9404688 \h 52PrestaShopHomePage PAGEREF _Toc9404689 \h 52ListingPage PAGEREF _Toc9404690 \h 52HomePage PAGEREF _Toc9404691 \h 52Tests using page object model PAGEREF _Toc9404692 \h 52Homework PAGEREF _Toc9404693 \h 54PROPERTIES FILE, DRIVER CLASS PAGEREF _Toc9404694 \h 54ConfigurationReader PAGEREF _Toc9404695 \h 54Driver class with configuration reader PAGEREF _Toc9404696 \h 55HomePage with configuration reader PAGEREF _Toc9404697 \h 56Test Base PAGEREF _Toc9404698 \h 57Properties file PAGEREF _Toc9404699 \h 58Tests with page object and configuration reader PAGEREF _Toc9404700 \h 58Tests with page object and configuration reader 2 PAGEREF _Toc9404701 \h 59HOMEWORK PAGEREF _Toc9404702 \h 61WAITS AND SYNCHRONIZATION PAGEREF _Toc9404703 \h 61Explicit wait PAGEREF _Toc9404704 \h 61Thread.sleep, implicit wait PAGEREF _Toc9404705 \h 62basic navigationTest casesopen browser, get page, get title1. Open chrome browser2. go to url ""3. Verify titleExpected title: Googledriver.getTitle(); --> get the title of the page, returns a stringOpen browser, get page, get URL1. Open chrome browser2. go to url ""3. Verify urlExpected url: ""driver.getCurrentUrl() --> gets the url of the current pageCODE EXAMPLE get page, get titlepublic class FirstSeleniumEver { public static void main(String[] args) { // Step 1 open chrome System.setProperty("webdriver.chrome.driver", "/Users/cybertekschool/Documents/selenium dependencies/drivers/chromedriver"); WebDriver driver = new ChromeDriver(); // Step 2. go to url "" driver.get("");// Step 3. Verify title// Expected title: Google String actualTitle = driver.getTitle(); System.out.println("actualTitle = " + actualTitle); String expectedTitle = "Google"; // verifying if (expectedTitle.equals(actualTitle)){ System.out.println("PASS"); } else { System.out.println("FAIL"); System.out.println("Expected: " + expectedTitle); System.out.println("Actual: " + actualTitle); } }} get, navigate to, back, forward, refreshpublic class FirstSelenium { public static void main(String[] args) { // we cannot open a browser without setting the path drivers // this line must come before creating the webdriver object // first argument is the type driver System.setProperty("webdriver.chrome.driver", // location of the driver "/Users/cybertekschool/Documents/selenium dependencies/drivers/chromedriver"); // this line open a chrome browser WebDriver driver = new ChromeDriver(); // open a website driver.get(""); driver.get(""); driver.navigate().to(""); driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh(); // refreshes the page // BREAK }} navigate to, back, forward public class SecondSelenium { public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "/Users/cybertekschool/Documents/selenium dependencies/drivers/geckodriver"); WebDriver driver = new FirefoxDriver(); // this line open firefox driver driver.get(""); driver.navigate().to(""); driver.navigate().back(); driver.navigate().forward(); }} get url /* 1. Open chrome browser2. go to url ""3. Verify urlExpected url: "" */public class VerifyURLTest { // THIS TEST IS SUPPOSED TO FAIL, mmy code is failing // your may pass public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/Users/cybertekschool/Documents/selenium dependencies/drivers/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get(""); String expectedUrl = ""; String actualUrl = driver.getCurrentUrl() ; if (expectedUrl.equals(actualUrl)){ System.out.println("PASS"); } else { System.out.println("FAIL"); System.out.println("actualUrl = " + actualUrl); System.out.println("expectedUrl = " + expectedUrl); } System.out.println(driver.getPageSource()); // gets the HTML of the page }}Basic locators, web element classTest casesBasic authentication Address bookOpen browserGo to username kexesobepu@Enter password passwordClick sign in buttonVerify username is displayed on pageVerify the title does not include Sign InBasic authentication Zero bankOpen browserGo to username usernameEnter password passwordClick sign in buttonVerify username is displayed on pageVerify the title Zero - Account SummarySearch AmazonOpen browserGo to any search termClick on search buttonVerify title contains the search termRetrieve passwordOpen browserGo to https:// the-internet.forgot_passwordEnter any emailClick on Retrieve passwordVerify url contains email_sentClick on linksOpen browserGo to https:// the-internet.Click link File downloadVerify title contains on downloadNavigate to previous pageClick link File uploadVerify title contains on uploadCODE EXAMPLE maximize browser, id, name, class name, sendkeys, clickpublic class BasicAuthenticationAddressBook { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/Users/cybertekschool/Documents/selenium dependencies/drivers/chromedriver"); WebDriver driver = new ChromeDriver(); // HOW TO MAXIMIZE THE PAGE// driver.manage().window().fullscreen(); // mac// driver.manage().window().maximize(); // windows driver.get(""); // finding element from page WebElement inputEmail = driver.findElement(By.id("session_email")); // enter the username inputEmail.sendKeys("kexesobepu@"); // find the password input box WebElement inputPassword = driver.findElement(By.id("session_password")); // enter password inputPassword.sendKeys("password"); // locates the sign in button WebElement signinButton = driver.findElement(By.name("commit")); System.out.println(driver.getTitle()); // clicks on the button signinButton.click(); System.out.println(driver.getTitle()); // located the username element WebElement username = driver.findElement(By.className("navbar-text")); String actualUsername = username.getText(); System.out.println(actualUsername); // Verify username is displayed on page if ("kexesobepu@".equals(actualUsername)){ System.out.println("PASS"); } else { System.out.println("FAIL"); System.out.println("EXPECTED: kexesobepu@"); System.out.println("actualUsername = " + actualUsername); } // verify title if ( !driver.getTitle().contains("Sign In") ) { System.out.println("PASS"); } else { System.out.println("FAIL"); System.out.println(driver.getTitle()); } }} implicit wait vs thread.sleep, tagname, sendkeyspublic class ImplicitWait { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "/Users/cybertekschool/Documents/selenium dependencies/drivers/chromedriver"); WebDriver driver = new ChromeDriver(); // this line makes the findElement method wait for some time when it cannot find an element // findElement method will keep trying to locate the element during the given duration driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get(""); driver.findElement(By.tagName("inpsdfsdfut")).sendKeys("asdfasdfd"); // HARD CODED WAIT Thread.sleep(5000); driver.get(""); }} id, name, linktext, partial linktext, sendkeys, clickpublic class LogOutTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/Users/cybertekschool/Documents/selenium dependencies/drivers/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get(""); WebElement inputEmail = driver.findElement(By.id("session_email")); inputEmail.sendKeys("kexesobepu@"); WebElement inputPassword = driver.findElement(By.id("session_password")); inputPassword.sendKeys("password"); WebElement signinButton = driver.findElement(By.name("commit")); signinButton.click(); WebElement lougOutLink = driver.findElement(By.linkText("Sign out")); lougOutLink.click(); WebElement homeLink = driver.findElement(By.partialLinkText("Hom")); homeLink.click(); }} tagnamepublic class RetrievePassword { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/Users/cybertekschool/Documents/selenium dependencies/drivers/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get(""); WebElement email = driver.findElement(By.tagName("input")); email.sendKeys("example@"); WebElement button = driver.findElement(By.tagName("button")); button.click(); } }handling different elements,: input, checkbox, radiobutton, dropdown; xpathTest casesVerify checkbox functionalityOpen browserGo to the first checkbox is not selectedVerify the second checkbox is selectedClick on the first checkboxVerify the first checkbox is selectedVerify the second checkbox is selectedClick on the second checkboxVerify the first checkbox is selectedVerify the second checkbox is not selectedMercury Tours radio button functionalityOpen browserGo to Login using username tutorial and password tutorialVerify Round Trip is selected by defaultVerify One Way is not selected by defaultClick one wayVerify Round Trip selected not selectedVerify One Way is selectedMercury Tours departure listOpen browserGo to Login using username tutorial and password tutorialVerify default Departing From value is AcapulcoVerify list of locations: Acapulco, Frankfurt, London, New York, Paris, Portland, San Francisco, Seattle, Sydney, ZurichTest Departing From dropdown functionality by changing different values input box/*1. open browser2. go to amazon3. enter search term and submit4. verify search box still contains the same search term */public class AmazonSearch { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); // get --> go to some url driver.get(""); String searchterm = "wooden spoon"; driver.findElement(By.id("twotabsearchtextbox")) .sendKeys(searchterm+ Keys.ENTER); String actual = driver. findElement(By.id("twotabsearchtextbox")) .getAttribute("value"); if (searchterm.equals(actual)) { System.out.println("PASS"); } else { System.out.println("FAIL"); System.out.println("actual = " + actual); System.out.println("searchterm = " + searchterm); } inputpublic class EtsyExample { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get(""); WebElement input = driver.findElement(By.id("search-query")); input.sendKeys("decal"); WebElement submit = driver.findElement(By.xpath("//button[@class='btn btn-primary']")); submit.click(); }} input/*go to enter email and submitverify email sent message on the next page"Your e-mail's been sent!" */public class SubmitEmail { public static void main(String[] args) { // setting driver path for chrome using the webdriver manager WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get(""); WebElement input = driver.findElement(By.id("email"));// input.sendKeys("somemeail@"+ Keys.ENTER); input.sendKeys("somemeail@"); input.submit(); String expected = "Your e-mail's been sent!"; String actual = driver.findElement(By.id("content")).getText(); if (actual.equals(expected)) { System.out.println("PASS"); } else { System.out.println("FAIL"); System.out.println("actual = " + actual); System.out.println("expected = " + expected); } }} dropdown public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get(""); // 1. we have to locate an element with tag select WebElement selectElement = driver.findElement(By.id("dropdown")); // 2. create select object using the webelement Select list = new Select(selectElement); // print the selected option String selectedOption = list.getFirstSelectedOption().getText(); System.out.println(selectedOption); // print all available options List<WebElement> options = list.getOptions(); System.out.println("options.size() = " + options.size()); for (WebElement option:options) { System.out.println(option.getText()); } // select different options // 1. by visible text list.selectByVisibleText("Option 1"); System.out.println("Selected option: " + list.getFirstSelectedOption().getText()); // 2. by visible index, count is 0 based list.selectByIndex(2); System.out.println("Selected option: " + list.getFirstSelectedOption().getText()); // 3. by value attribute list.selectByValue("1"); System.out.println("Selected option: " + list.getFirstSelectedOption().getText()); }} radio buttonspublic class RadioButtons { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get(""); // verify blue and red not checked WebElement blue=driver.findElement(By.id("gwt-debug-cwRadioButton-color-blue-input")); WebElement red=driver.findElement(By.id("gwt-debug-cwRadioButton-color-red-input")); System.out.println("DEFAULT"); System.out.println("blue: " + blue.isSelected()); System.out.println("red: " + red.isSelected()); // check blue System.out.println("Clicking on blue"); blue.click(); // verify blue checked, red not checked System.out.println("blue: " + blue.isSelected()); System.out.println("red: " + red.isSelected()); // check red System.out.println("Clicking red"); red.click(); // verify blue not checked, red is checked System.out.println("blue: " + blue.isSelected()); System.out.println("red: " + red.isSelected()); } // 3.15 break} Checkboxes/*go to monday is not selectedselect mondayverify monday is selectedunselect monday */public class ReallyCheckboxes { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); WebElement monday = driver.findElement(By.id("gwt-debug-cwCheckBox-Monday-input"));// System.out.println(monday.isSelected());//// monday.click();//// System.out.println(monday.isSelected());//// monday.click();//// System.out.println(monday.isSelected());//// System.out.println(monday.isSelected()); if (!monday.isSelected()){ monday.click(); } System.out.println(monday.isSelected()); }}TestNG Intro Assertionspublic class AssertionsDemo { @Test public void test1(){ String a = "A"; String b = "A"; Assert.assertEquals(a, b); // comparing a to b } @Test public void test2(){ String a = "A"; String b = "AAA"; Assert.assertEquals(a, b); // comparing a to b, first param is actual second is expected } @Test public void test3(){ String a = "ADAFD"; String b = "AAA"; Assert.assertTrue(b.contains(a)); Assert.assertTrue(true); System.out.println("DONE"); } @Test public void test4(){ String a = "ADAFD"; String b = "AAA"; Assert.assertTrue(b.contains(a), b + " should have contained "+ a); } @Test public void test5(){ Assert.assertTrue(false); }} @beforemethod @aftermethodpublic class GoogleTest { WebDriver driver; @BeforeMethod public void setUp(){ WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.get(""); } @Test public void test(){ Assert.assertTrue(driver.getTitle().contains("asdf")); } @AfterMethod public void tearDown(){ driver.quit(); }} beforemethod vs before class public class DifferentAnnotations {@Test public void testOne(){ System.out.println("This is test one"); } @BeforeMethod public void beforeMethod(){ System.out.println("This is before method"); } @Test public void testTwo(){ System.out.println("This is test two"); } @BeforeClass public void beforeClass(){ System.out.println("This is before class"); }} after method vs after classpublic class DifferentAnnotations2 { public void testOne(){ System.out.println("This is test one"); } @Test public void testTwo(){ System.out.println("This is test two"); } @AfterMethod public void afterMethod(){ System.out.println("This is after method"); } @AfterClass public void afterClass(){ System.out.println("This is after class"); }} mixed annotationspublic class MixedAnnotations {Webriver driver; @BeforeClass public void beforeClass(){ System.out.println("Setting up the drivers here"); WebDriverManager.chromedriver().setup(); } @BeforeMethod public void setUpTMethod(){ System.out.println("Opening a browser"); driver = new ChromeDriver(); System.out.println("go to website and login"); driver.get(""); } @Test public void testOne(){ System.out.println("Testing testing testing: account info"); } @AfterMethod public void afterMethod(){ System.out.println("logout"); System.out.println("closing browser"); driver.quit(); } @AfterClass public void afterClass(){ System.out.println("report everything"); } @Test public void testTwo(){ System.out.println("Testing testing testing: payment"); } @Test public void testThree(){ System.out.println("Testing testing testing: another thing"); }}testng order, depends on depends onpublic class DependenciesTest { @Test public void login(){ System.out.println("login"); Assert.assertTrue(false); } @Test(dependsOnMethods = "login") public void zbuySth(){ System.out.println("buy buy baby"); } @Test(priority = 5) public void homePage(){ System.out.println("home page");} Mixed dependenciespublic class MixedUpDependencies { @Test() public void openBrowser(){ System.out.println("opening browser"); } @Test(dependsOnMethods = "openBrowser") public void login(){ System.out.println("login"); } @AfterMethod public void cleanUp(){ System.out.println("close browser"); }} more dependenciespublic class MoreDependenciesTest { @Test() public void openBrowser(){ System.out.println("opening browser"); } @Test(dependsOnMethods = "openBrowser") public void login(){ System.out.println("login"); Assert.assertTrue(false); } @Test(dependsOnMethods = "login" ) public void logOut(){ System.out.println("logout"); } priority, test that fails// THIS TEST WILL FAIL/*1. open browser2.go to that default dropdown option is all4.verify that all options are sorted alphabetically5.Click on the menu icon on the left6.click on Full Store directory7.capture all of the main department names in the page.8.verify that departments names are sorted alphabetically9.verify that all departments names are listed in the dropdown from step 4 */public class DepartmentsTest { WebDriver driver; Select allDepartments; @BeforeClass public void setUpMethod() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get(""); } // verify that default dropdown option is all @Test (priority = 0) public void testDefaultValue() { // finding the element with a select tag WebElement selectElement = driver.findElement(By.id("searchDropdownBox")); // create a Select class object allDepartments = new Select(selectElement); // get the current selected option String selectedOption = allDepartments.getFirstSelectedOption().getText(); Assert.assertEquals(selectedOption, "All"); }// 4.verify that all options are sorted alphabetically @Test (priority = 1) public void sortAlphabetical(){ // using the compare to method, we will compare each element in the list to the next one for (int i = 0; i < allDepartments.getOptions().size()-1; i++) { String current = allDepartments.getOptions().get(i).getText(); String next = allDepartments.getOptions().get(i+1).getText(); System.out.println("comparing: " + current + " with "+ next); Assert.assertTrue(pareTo(next)<=0); } }// 5.Click on the menu icon on the left// 6.click on Full Store directory// 7.capture all of the main department names in the page.// 8.verify that departments names are sorted alphabetically @Test public void mainDepartmentsTest() throws InterruptedException {// 5.Click on the menu icon on the left driver.findElement(By.cssSelector("i.hm-icon.nav-sprite")).click(); // click on Full Store directory // waiting because it is taking time for element to load and be clickable Thread.sleep(2000); driver.findElement(By.cssSelector("a[href='/gp/site-directory?ref_=nav_em_T1_0_2_2_33__fullstore']")).click(); // capture all of the main department names in the page. List<WebElement> mainDepts = driver.findElements(By.cssSelector("h2.fsdDeptTitle")); for (WebElement option : mainDepts) { System.out.println(option.getText()); } } @AfterClass public void tearDown(){// driver.quit(); }}Tabs, frames, alertsLINKSAlerts Pop ups Windows pop uppublic class HTMLPopup { WebDriver driver; @BeforeMethod public void setUp() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); } @AfterMethod public void cleanUp() throws InterruptedException { Thread.sleep(5000); driver.quit(); } @Test public void doNotDestroyTheWorldTest() { driver.get(""); driver.findElement(By.xpath("//span[.='Destroy the World']")).click(); // locate an element in the pop up window and click driver.findElement(By.xpath("//span[.='No']")).click(); } @Test public void oopsTest() { driver.get(""); // trigger the pop up driver.findElement(By.xpath("(//button[@class='preview'])[2]")).click(); // close the pop up driver.findElement(By.xpath("//button[.='OK']")).click(); }}Iframe/*1. create a new class IframeDemo2. go to url . enter text in the text editor*/import io.github.bonigarcia.wdm.WebDriverManager;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.testng.annotations.Test;import java.util.concurrent.TimeUnit;public class IframeDemo { @Test public void test(){ WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get(""); // locate the iframe WebElement iframe = driver.findElement(By.id("mce_0_ifr")); // switch to iframe driver.switchTo().frame(iframe); driver.findElement(By.tagName("body")). sendKeys("ddeee dddedd dd"); }}Iframe switch optionspublic class SwitchOptions { WebDriver driver; @BeforeMethod public void setUp(){ WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.get(""); } @AfterMethod public void leanUp(){ driver.quit(); } @Test public void switchByElement(){ // locate the iframe WebElement iframe = driver.findElement(By.id("mce_0_ifr")); // switch to iframe driver.switchTo().frame(iframe); driver.findElement(By.tagName("body")). sendKeys("ddeee dddedd dd"); } @Test public void switchById(){ // switch to iframe driver.switchTo().frame("mce_0_ifr"); driver.findElement(By.tagName("body")). sendKeys("ddeee dddedd dd"); } @Test public void switchByIndex(){ // switch to iframe driver.switchTo().frame(0); driver.findElement(By.tagName("body")). sendKeys("ddeee dddedd dd"); }}Javascript alertspublic class JSAlerts { WebDriver driver; @BeforeMethod public void setUp() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); } @AfterMethod public void cleanUp() throws InterruptedException { Thread.sleep(5000); driver.quit(); } @Test public void oopsTest(){ driver.get(""); // trigger the pop up driver.findElement(By.xpath("(//button[@class='preview'])[1]")).click(); // switch to alert Alert alert = driver.switchTo().alert(); alert.accept(); // clicking OK on a pop up } @Test public void dismiss(){ driver.get(""); // trigger the pop up driver.findElement(By.xpath("//button[@onclick='jsConfirm()']")).click(); Alert alert = driver.switchTo().alert(); alert.dismiss(); // clicking Cancel on a pop up } @Test public void alertText(){ driver.get(""); // trigger the pop up driver.findElement(By.xpath("//button[@onclick='jsPrompt()']")).click(); Alert alert = driver.switchTo().alert(); alert.sendKeys("Hello"); // typing on the alert alert.accept(); }}Switch tabspublic class TabsExample { WebDriver driver; @BeforeMethod public void setUp(){ WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.get(""); }// @AfterMethod public void cleanUp() throws InterruptedException { Thread.sleep(5000); driver.quit(); }/*Test case:go to on click "Click here"verify that new title is "New Window"verify that new title is not "The Internet"*/ @Test public void changeTab(){ System.out.println(driver.getWindowHandles().size()); System.out.println(driver.getWindowHandle()); driver.findElement(By.linkText("Click Here")).click(); System.out.println(driver.getWindowHandles().size()); // change to the new tab Set<String> windowHandles = driver.getWindowHandles(); System.out.println("***************"); for (String handle : windowHandles) { System.out.println(handle); // switching tabs driver.switchTo().window(handle); System.out.println(driver.getTitle()); if (driver.getTitle().equals("New Window")){ break; } } Assert.assertEquals( driver.getTitle(),"New Window"); Assert.assertNotEquals( driver.getTitle(),"The Internet"); }/** go to * click ont Try it Yourself* verify the url of the new tab contains "default"* */ @Test public void changeTab2(){ driver.get(""); driver.findElement(By.linkText("Try it Yourself ?")).click(); // title of the second Tryit Editor v3.6 // get all handles // switch 1 by one // if the title is the right, break the loop for(String handle: driver.getWindowHandles()){ driver.switchTo().window(handle); if (driver.getTitle().equals("Tryit Editor v3.6")){ break; } } Assert.assertTrue(driver.getCurrentUrl().contains("default")); System.out.println(driver.getWindowHandles().size()); driver.close(); System.out.println(driver.getWindowHandles().size()); }}HOMEWORKWeb Order Login Tests Homework.pdf??PRESTA SHOP PART I.pdfSOFT ASSERTIONS, TEST BASE, ACTIONS, FILE DOWNLOADTest basepublic abstract class TestBase { protected WebDriver driver; protected Actions actions; protected SoftAssert softAssert; @BeforeClass public void setUpClass(){ WebDriverManager.chromedriver().setup(); } @BeforeMethod public void setUpMethod(){ driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); actions = new Actions(driver); softAssert = new SoftAssert(); } @AfterMethod public void tearDownMethod(){ driver.quit(); softAssert.assertAll(); }}Actions double clickpublic class DoubleClickTest extends TestBase { @Test public void test() { driver.get(""); driver.switchTo().frame("iframeResult"); // create actons object Actions actions = new Actions(driver); // identify the webelement on which we double click WebElement text = driver.findElement(By.id("demo")); // double click on element // we need to add perform at the end of any action actions.doubleClick(text).perform(); Assert.assertTrue(text.getAttribute("style").contains("red")); }}Actions drag and droppublic class DragAndDrop extends TestBase { @Test public void test(){ driver.get(""); WebElement source = driver.findElement(By.id("draggable")); WebElement target = driver.findElement(By.id("droptarget")); // pass the variable in the correct order, first one is source, second one is target actions.dragAndDrop(source, target).perform(); } @Test public void test2(){ driver.get(""); WebElement source = driver.findElement(By.id("draggable")); WebElement target = driver.findElement(By.id("droptarget")); // write the steps for doing the drag and drop operation // without using the dragAndDrop(); method // when we use multiple actions we need to add build() before we perform() // actions.clickAndHold(source).moveToElement(target).release().build().perform(); }}Actions hoverpublic class HoverTest extends TestBase { @Test public void test(){ driver.get(""); WebElement signIn = driver.findElement(By.xpath("//span[.='Hello. Sign in']")); // moving the mouse on top of the given element actions.moveToElement(signIn).perform(); driver.findElement(By.xpath("//span[.='Your Hearts']")).click(); Assert.assertTrue(driver.getTitle().contains("Interesting")); } @Test public void test2(){ driver.get(""); WebElement help = driver.findElement(By.xpath("(//a[.='Help'])[2]")); actions.moveToElement(help).perform(); }}Verify file existspublic class FileExistsTest { @Test public void test() { // get the current folder String current = System.getProperty("user.dir"); System.out.println(current); // get the user folder String userFolder = System.getProperty("user.home"); System.out.println(userFolder); // MAC USE THIS LINE String path = userFolder + "/Downloads/test.txt"; // WINDOWS USE THIS LINE// String path = userFolder + "\\Downloads\\test.txt"; System.out.println(path); // Files.exists(Paths.get() : returns true if file exists in the parameter provided Assert.assertTrue(Files.exists(Paths.get(path))); }}Test that extends test base/*open chromego to googlesearch for selenium cookbookverify title contains the search term */public class GoogleDemo extends TestBase { @Test public void titleTest(){ driver.get(""); driver.findElement(By.name("q")).sendKeys("selenium cookbook"+ Keys.ENTER); Assert.assertTrue(driver.getTitle().contains("selenium cookbook")); }Soft assert 1public class EtsyWithSoftAssert extends TestBase { @Test public void test() { driver.get(""); driver.findElement(By.id("search-query")).sendKeys("gift" + Keys.ENTER); softAssert.assertTrue(driver.getTitle().contains("gift"), "title did not match"); Assert.assertTrue(driver.getTitle().contains("AAA")); }}Soft assert 2public class SoftAssertionExample { @Test public void test1(){ System.out.println("starting"); Assert.assertTrue(false); System.out.println("done"); } @Test public void test2(){ SoftAssert softAssert = new SoftAssert(); System.out.println("starting"); softAssert.assertTrue(false); softAssert.assertEquals("google", "etsy"); System.out.println("done"); softAssert.assertAll(); System.out.println("really"); } @Test public void test3(){ SoftAssert softAssert = new SoftAssert(); System.out.println("starting"); softAssert.assertTrue(false); Assert.assertTrue(false); System.out.println("done"); softAssert.assertAll(); }}HOMEWORKPRESTA SHOP PART II.pdfFILE UPLOAD. WEB TABLESTable: select whole table, select column names, select certain row, select by coordinate, select row, table size, indexXpath: index, parentpublic class WebTablesExample extends TestBase {/*Prints the whole table */ @Test public void printWholeTable(){ login(); WebElement table = driver.findElement(By.id("ctl00_MainContent_orderGrid")); System.out.println(table.getText()); } public void login(){ driver.get(""); driver.findElement(By.id("ctl00_MainContent_username")). sendKeys("Tester"); driver.findElement(By.id("ctl00_MainContent_password")). sendKeys("test"+ Keys.ENTER); }/*printing the headers of the table */ @Test public void printAllHeaders(){ login(); List<WebElement> headers = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']//th")); for (WebElement header:headers) { System.out.println(header.getText()); } }/*prints the number of rowsprints all rows === prints the whole againprints the certain based on indexwe got all rows in a list, and selected a row from that list */ @Test public void printRow(){ login(); List<WebElement> allRows = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']/tbody/tr")); System.out.println("number of rows: " + allRows.size()); for (WebElement header:allRows) { System.out.println(header.getText()); } // print the nth System.out.println("printing row " + 4); System.out.println(allRows.get(3).getText()); } /* print the size: columns and rows in a table */ @Test public void printTableSize(){ login(); List<WebElement> allRows = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']/tbody/tr")); System.out.println("number of rows: " + allRows.size()); List<WebElement> allHeaders = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']/tbody/tr[1]/th")); System.out.println("number of cols "+allHeaders.size()); } /* print a row without using a list */ @Test public void printRow2(){ login(); WebElement row = driver.findElement(By.xpath( "//table[@id='ctl00_MainContent_orderGrid']/tbody/tr[5]")); System.out.println(row.getText()); } /* print all the cells of a a row whose index is given in the xpath */ @Test public void printAllCellsInOneRow(){ login(); List<WebElement> cells = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']/tbody/tr[4]/td")); for (WebElement header:cells) { System.out.println(header.getText()); } } /* print by coordinates : based on row and column number */ @Test public void printByCoordinates(){ login(); WebElement cell = driver.findElement( By.xpath("//table[@id='ctl00_MainContent_orderGrid']/tbody/tr[6]/td[11]")); System.out.println(cell.getText()); System.out.println(getCell(6,11).getText()); } public WebElement getCell(int row, int col){ String xpath = "//table[@id='ctl00_MainContent_orderGrid']/tbody/tr["+row+"]/td["+col+"]"; return driver.findElement(By.xpath(xpath)); }/*print all the values in single column */ @Test public void printColumn(){ login(); List<WebElement> allNames = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']/tbody/tr/td[2]")); for (WebElement header:allNames) { System.out.println(header.getText()); } } /* find the select checkbox for a given name */ @Test public void selectCheckbox(){ login(); WebElement checkbox = driver.findElement (By.xpath("//td[.='Susan McLaren']/../td[1]/input")); System.out.println(checkbox.isSelected()); checkbox.click(); System.out.println(checkbox.isSelected()); } /* verify that name 'Mark Smith' exists in the names column verify that city 'Whitestone, British' exists in the cities column */ @Test public void test(){ login(); int nameIndex = getColumnIndex("Name"); System.out.println(nameIndex); List<WebElement> allNames = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']/tbody/tr/td["+nameIndex+"]")); boolean found =false; for (int i = 0; i < allNames.size(); i++) { if (allNames.get(i).getText().equals("Mark Smith")){ found = true; break; } } Assert.assertTrue(found); found = false; int cityIndex = getColumnIndex("City"); List<WebElement> allCities = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']/tbody/tr/td["+cityIndex+"]")); for (int i = 0; i < allCities.size(); i++) { if (allCities.get(i).getText().equals("Whitestone, British")){ found = true; break; } } Assert.assertTrue(found); } /* gets a column name as a parameters returns the index of the column name */ public int getColumnIndex(String column){ List<WebElement> allHeader = driver.findElements( By.xpath("//table[@id='ctl00_MainContent_orderGrid']//th")); for (int i = 0; i < allHeader.size(); i++) { if (allHeader.get(i).getText().equals(column)){ return i+1; } } return 0; }}HOMEWORKWeb Orders web table tests??2016 Olympics??Porsche-1.pdf?EXCEPTIONS REVIEW, VERIFY ELEMENT EXISTSNegative verifications Verify element does NOT existpublic class verifyTextDisappearTest extends TestBase { @Test public void verify1() { driver.get(""); WebElement text = driver.findElement(By.id("myDIV")); Assert.assertTrue(text.isDisplayed()); WebElement button = driver.findElement(By.xpath("//button[.='Toggle Hide and Show']")); button.click(); Assert.assertFalse(text.isDisplayed()); } @Test public void verify2() { driver.get(""); driver.switchTo().frame("iframeResult"); WebElement text = driver.findElement(By.xpath("//body/p")); Assert.assertTrue(text.isDisplayed()); WebElement button = driver.findElement(By.xpath("//body/button")); button.click(); Assert.assertFalse(elementDisplayed(By.xpath("//body/p"))); } /** * takes a locator and returns if element matching this locator exists * * @param by * @return */ public boolean elementDisplayed(By by) { // try find it // if cant find it, return false try { return driver.findElement(by).isDisplayed(); } catch (NoSuchElementException e) { return false; } } public boolean elementDisplayedS(By by) { // if the locator mathches the list will not be empty // if the locator does not match anything the list will be empty return !driver.findElements(by).isEmpty(); }}PAGE OBJECT MODELTest CasesWrong username1. go to website??(Links to an external site.)Links to an external site.?2. try to login with wrong username3. verify error message?Invalid Login or Password.Wrong password1. go to website? . try to login with wrong password3. verify error message?Invalid Login or Password.No username1. go to website . try to login no username3. verify error message?Invalid Login or Password.No password1. go to website . try to login with no password3. verify error message?Invalid Login or Password.?CODE EXAMPLEDriver classpublic class Driver { private static WebDriver driver; private Driver(){} public static WebDriver getDriver(){ if (driver==null){ WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); } return driver; } public static void closeDriver(){ if (driver!=null){ driver.quit(); driver = null; } }}Test Base using driver classpublic abstract class TestBase { protected WebDriver driver; protected Actions actions; protected SoftAssert softAssert; @BeforeMethod public void setUpMethod(){ driver = Driver.getDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); actions = new Actions(driver); softAssert = new SoftAssert(); } @AfterMethod public void tearDownMethod(){ Driver.closeDriver(); softAssert.assertAll(); }}PrestaShopHomePagepublic class PrestashopHomePage { public PrestashopHomePage(){ PageFactory.initElements(Driver.getDriver(), this); } @FindBy (linkText = "Sign in") public WebElement signIn; public WebElement product(String productName){ String xpath = "(//h5/a[@title='"+productName+"'])[1]"; return Driver.getDriver().findElement(By.xpath(xpath)); }}ListingPagepublic class ListingPage { public ListingPage(){ PageFactory.initElements(Driver.getDriver(), this); } @FindBy(xpath = "asdfasfda") public WebElement address; @FindBy(xpath = "asdfasfda") public WebElement agent; @FindBy(xpath = "asdfasfda") public WebElement map;}HomePagepublic class HomePage { public HomePage(){ PageFactory.initElements(Driver.getDriver(), this); } @FindBy(id="ctl00_MainContent_username") public WebElement username; @FindBy(id="ctl00_MainContent_password") public WebElement password; @FindBy(id="ctl00_MainContent_login_button") public WebElement loginButton; @FindBy(id="ctl00_MainContent_status") public WebElement errorMessage; public void login(String username, String password){ this.username.sendKeys(username); this.password.sendKeys(password); loginButton.click(); } public void open(){ Driver.getDriver().get(""); }}Tests using page object modelpublic class ErrorMessageValidationTest extends TestBase { @Test public void wrongEmailTest(){ HomePage homePage = new HomePage(); driver.get(""); homePage.username.sendKeys("admin"); homePage.password.sendKeys("test"); homePage.loginButton.click(); String error = "Invalid Login or Password."; String actualError = homePage.errorMessage.getText(); Assert.assertEquals(actualError, error); } @Test public void wrongPasswordTest(){ HomePage homePage = new HomePage(); driver.get(""); homePage.username.sendKeys("Tester"); homePage.password.sendKeys("wrong password"); homePage.loginButton.click(); String expextedError = "Invalid Login or Password."; String actualError = homePage.errorMessage.getText(); Assert.assertEquals(actualError, expextedError); } @Test public void blankUsername(){ HomePage homePage = new HomePage(); homePage.open(); homePage.login("", "test"); String expextedError = "Invalid Login or Password."; String actualError = homePage.errorMessage.getText(); Assert.assertEquals(actualError, expextedError); }// this is just a method which does not do anything// @Test public void test(){ ListingPage nilesLane = new ListingPage(); ListingPage palmetLane = new ListingPage(); PrestashopHomePage prestashopHomePage = new PrestashopHomePage(); WebElement tshirt = prestashopHomePage.product("tshirt"); WebElement dress = prestashopHomePage.product("dress"); }}Homework?PRESTA SHOP PART III-1.pdfPROPERTIES FILE, DRIVER CLASSConfigurationReaderpublic class ConfigurationReader { private static Properties properties; // read the properties file static { String path = "configuration.properties"; try { FileInputStream fileInputStream = new FileInputStream(path); properties = new Properties(); properties.load(fileInputStream); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } // returns the value of specific property public static String getProperty(String property){ return properties.getProperty(property); }}Driver class with configuration readerpublic class Driver { private static WebDriver driver; private Driver(){} public static WebDriver getDriver(){ if (driver==null){ String browser = ConfigurationReader.getProperty("browser"); switch (browser){ case "chrome": WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); break; case "firefox": WebDriverManager.firefoxdriver().setup(); driver = new FirefoxDriver(); break; case "ie": WebDriverManager.iedriver().setup(); driver = new InternetExplorerDriver(); break; } } return driver; } public static void closeDriver(){ if (driver!=null){ driver.quit(); driver = null; } }}HomePage with configuration readerpublic class HomePage { public HomePage(){ PageFactory.initElements(Driver.getDriver(), this); } @FindBy(id="ctl00_MainContent_username") public WebElement username; @FindBy(id="ctl00_MainContent_password") public WebElement password; @FindBy(id="ctl00_MainContent_login_button") public WebElement loginButton; @FindBy(id="ctl00_MainContent_status") public WebElement errorMessage; public void login(String username, String password){ this.username.sendKeys(username); this.password.sendKeys(password); loginButton.click(); } public void open(){ Driver.getDriver().get(ConfigurationReader.getProperty("url")); }}Test Basepublic abstract class TestBase { protected WebDriver driver; protected Actions actions; protected SoftAssert softAssert; @BeforeMethod public void setUpMethod(){ driver = Driver.getDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); actions = new Actions(driver); softAssert = new SoftAssert(); } @AfterMethod public void tearDownMethod(){ Driver.closeDriver(); softAssert.assertAll(); }}Properties fileurl= with page object and configuration readerpublic class LoginTestWithProperties extends TestBase { @Test public void readPropertyTest(){ driver.get(ConfigurationReader.getProperty("url")); HomePage homePage = new HomePage(); String username = ConfigurationReader.getProperty("username"); String password = ConfigurationReader.getProperty("password"); homePage.login(username, password); }}Tests with page object and configuration reader 2public class ErrorMessageValidationTest extends TestBase { @Test public void wrongEmailTest(){ HomePage homePage = new HomePage(); driver.get(ConfigurationReader.getProperty("url")); homePage.username.sendKeys("admin"); homePage.password.sendKeys("test"); homePage.loginButton.click(); String error = "Invalid Login or Password."; String actualError = homePage.errorMessage.getText(); Assert.assertEquals(actualError, error); } @Test public void wrongPasswordTest(){ HomePage homePage = new HomePage(); driver.get(""); homePage.username.sendKeys("Tester"); homePage.password.sendKeys("wrong password"); homePage.loginButton.click(); String expextedError = "Invalid Login or Password."; String actualError = homePage.errorMessage.getText(); Assert.assertEquals(actualError, expextedError); } @Test public void blankUsername(){ HomePage homePage = new HomePage(); homePage.open(); homePage.login("", "test"); String expextedError = "Invalid Login or Password."; String actualError = homePage.errorMessage.getText(); Assert.assertEquals(actualError, expextedError); }// this is just a method which does not do anything// @Test public void test(){ ListingPage nilesLane = new ListingPage(); ListingPage palmetLane = new ListingPage(); PrestashopHomePage prestashopHomePage = new PrestashopHomePage(); WebElement tshirt = prestashopHomePage.product("tshirt"); WebElement dress = prestashopHomePage.product("dress"); }}HOMEWORKPRESTA SHOP PART IV.pdf?WAITS AND SYNCHRONIZATIONExplicit waitpublic class ExplicitWaitExample { @Test public void test() throws InterruptedException { Driver.getDriver().get(""); // click on enable Driver.getDriver().findElement(By.xpath("//form[@id='input-example']//button")).click(); // WebDriverWait class used to explicit waits // just creating onject, waiting does not happen yet WebDriverWait wait = new WebDriverWait(Driver.getDriver(), 10); // wait.until() : this is when wait happens // we are waiting for certain element this this xpath to be clickable wait.until( ExpectedConditions.elementToBeClickable( By.xpath("//input[@type='text']"))); // enter text Driver.getDriver().findElement(By.xpath("//input[@type='text']")).sendKeys("hello world"); }}Thread.sleep, implicit waitpublic class SleepAndImplicitWaitExample { WebDriver driver; @BeforeMethod public void setUp(){ driver = Driver.getDriver(); } @AfterMethod public void tearDown() throws InterruptedException {// Driver.closeDriver(); } @Test public void testSleep() throws InterruptedException { driver.get(""); driver.findElement(By.tagName("button")).click(); Thread.sleep(10000); System.out.println(driver.findElement(By.id("finish")).getText()); } @Test public void implicitWait(){ // please wait when you are trying to find and element but cannot find it driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get(""); driver.findElement(By.tagName("button")).click(); System.out.println(driver.findElement(By.id("finish")).getText()); } @Test public void implicitWait2(){ driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get(""); // click on remove button driver.findElement(By.cssSelector("form#checkbox-example>button")).click(); // print the message System.out.println(driver.findElement(By.id("message")).getText()); // click on add button driver.findElement(By.cssSelector("form#checkbox-example>button")).click(); // verify checkbox is displayed System.out.println(driver.findElement(By.id("checkbox")).isDisplayed()); }} ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download