Automation QA Testing Course Content

Showing posts with label Junit. Show all posts
Showing posts with label Junit. Show all posts

ProgramS Using Junit Framework

package junitprograms;

import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

class GoogleTest {

private static WebDriver driver=null;
private static WebDriverWait wait=null;

@BeforeAll
static void setUpBeforeClass() throws Exception {
System.out.println("Executing the @BeforeAll - setUpBeforeClass() ");
//set the chromedriver.exe path
System.setProperty("webdriver.chrome.driver", "D:\\webdriverjars\\executables\\chromedriver_win32\\chromedriver.exe");
//interface refobj=new implementingclass();
driver=new ChromeDriver();
//maximize the window
driver.manage().window().maximize();
//add implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//create object for WebDriverWait class
wait=new WebDriverWait(driver,30);

}

@AfterAll
static void tearDownAfterClass() throws Exception {
System.out.println("Executing the @AfterAll -tearDownAfterClass() ");
driver.close();
}

@BeforeEach
void setUp() throws Exception {
System.out.println("Executing @BeforeEach - setUp() ...");
//open the google.com
driver.get("https://google.com");
wait.until(ExpectedConditions.titleContains("Google"));
Assert.assertEquals("Google", driver.getTitle());
}

@AfterEach
void tearDown() throws Exception {
//clear the cookies
System.out.println("executing the @AfterEach");
driver.manage().deleteAllCookies();
System.out.println("Cleared the cookies in @AfterEach");
}

@Test
void testGoogleLogo() {
System.out.println("Executing the @Test -testGoogleLogo() ");
//identify the Google logo element
WebElement glogo=driver.findElement(By.id("hplogo"));
//fetch the tooltip of the logo
String tp=glogo.getAttribute("title");
System.out.println("glogo tooltip is-->"+tp);

Point p=glogo.getLocation();
System.out.println("glogo x coordinate:"+p.getX()+" y coordinate :"+p.getY());

Dimension d=glogo.getSize();
System.out.println("height of the logo:"+d.getHeight()+" width: "+d.getWidth());

System.out.println("End of the @Test -testGoogleLogo() ");
}

@Test
public void testGoogleSearch() {
System.out.println("Executing the @Test -testGoogleSearch() ");
//type the selenium keyword in search editbox
driver.findElement(By.name("q")).sendKeys("selenium");
//submit on the search editbox
driver.findElement(By.name("q")).submit();

//verify the search results page title
wait.until(ExpectedConditions.titleContains("selenium - Google Search"));
//verify the search results count text is present in the webpage or not.
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("result-stats")));
//fetch the search results count text
String txt=driver.findElement(By.cssSelector("div#result-stats")).getText();
System.out.println("Searc hresults text is-->"+txt);
//String txt="About 4,71,00,000 results (0.52 seconds) ";

//extract the only count from search results count text using split(delimiter) --String[]
String[] str=txt.split(" ");
//str[]=["About","4,71,00,000","results","(0.52","seconds)]
//         0        1             2         3      4
System.out.println("results text is-->"+str[1]);
System.out.println("End of the @Test -testGoogleSearch() ");
}

}
========================================================================
HEROKUAPP WebSite LOGIN SCENARIOS
SCENARIO:
 1)Open the browser 
2)open the url :http://the-internet.herokuapp.com/
3)Verify the Page title and page heading
4)Click on Form Authentication link
5)Verify the login page Addressbar url and page heading
6)Login with valid credentials
7)Verify the secure Area page heading and success message
8)click on Logout button
9)Login with Validusername and invalid password
10)Verify the Error message
11)Login with Invalidusername and valid password
12)Verify the Error message
13)Login with InvalidCrdentials
14)Verify the Error Message
15)close the browser
----------------------------------------------------------------------------------------------------------------
package junitprograms;

import static org.junit.jupiter.api.Assertions.*;

import java.time.Duration;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

class HerokuAppLoginTest {
private static WebDriver driver = null;
private static WebDriverWait wait = null;

@BeforeAll
static void setUpBeforeClass() throws Exception {
// set the chromedriver.exe file path
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome971\\chromedriver_win32\\chromedriver.exe");
// interface refvar=new implementedclass();
driver = new ChromeDriver();

// maximize the window
driver.manage().window().maximize();

// add implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));

// open the url in browser
driver.get("http://the-internet.herokuapp.com/");

// create Object for WebDriverWait class
wait = new WebDriverWait(driver, Duration.ofMillis(30000));

wait.until(ExpectedConditions.titleContains("The Internet"));
// wait for the home page heading css=tagname.classvalue
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h1.heading")));
// fetch the header text
String headertxt = driver.findElement(By.cssSelector("h1.heading")).getText();
// assertEquals()
Assertions.assertEquals(headertxt, "Welcome to the-internet");
// assertTrue()
Assertions.assertTrue(driver.getPageSource().contains(headertxt));
// click on Form Authentication
driver.findElement(By.linkText("Form Authentication")).click();

}

@AfterAll
static void tearDownAfterClass() throws Exception {
if (driver != null) {
driver.quit();
}
}

@BeforeEach
void setUp() throws Exception {
// wait for the url
wait.until(ExpectedConditions.urlContains("http://the-internet.herokuapp.com/login"));
// wait for the page heading
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='content']/div/h2")));
// fetch teh header text Loginpage
String loginpgheadertxt = driver.findElement(By.cssSelector("div#content>div>h2")).getText();
// using assertEquals()
Assertions.assertEquals("Login Page", loginpgheadertxt);
// using assertTrue()
Assertions.assertTrue(driver.getPageSource().contains(loginpgheadertxt));

}

@AfterEach
void tearDown() throws Exception {
// clear the cookies
driver.manage().deleteAllCookies();
}

@Test
void testWithValidCredentials() {
System.out.println("started executing the testWithValidCredentials()....");
doLogin("tomsmith", "SuperSecretPassword!");
// driver.findElement(By.xpath("//button[@type='submit']")).submit();
// wait for the http://the-internet.herokuapp.com/secure
wait.until(ExpectedConditions.urlToBe("http://the-internet.herokuapp.com/secure"));
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='flash-messages']/div")));
// waiting for the secureArea headertext
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div#content>div>h2")));
// assertTrue
Assertions.assertTrue(driver.getPageSource().contains("Secure Area"));
// click on logout button
driver.findElement(By.cssSelector("a.button.secondary.radius")).click();

}

@Test
public void testValidUserNameInvalidPassword() {
System.out.println("started executing the testValidUserNameInvalidPassword()....");
doLogin("tomsmith", "gfads576a5s");
verifyErrorMessage("Your password is invalid!");
}
@Test
public void testInvalidUserNameAndValidPassword() {
System.out.println("started executing the testInvalidUserNameAndValidPassword()....");
doLogin("ksjdfhksjdf", "SuperSecretPassword!");
verifyErrorMessage("Your username is invalid!");
}
@Test
public void testWithInvalidCrdentials() {
System.out.println("started executing the testWithInvalidCrdentials()....");
doLogin("ksjdfhksjdf", "73642874382!");
verifyErrorMessage("Your username is invalid!");
}
/**
 * this method is used to do a login using usernamd and pasword
 * @param uname
 * @param pwd
 */
private void doLogin(String uname, String pwd) {
// type the username value in usernameTextbox
driver.findElement(By.id("username")).sendKeys(uname);
// type the password in passwordtextbox
driver.findElement(By.name("password")).sendKeys(pwd);
// click on Login button
driver.findElement(By.className("radius")).click();
}
private void verifyErrorMessage(String msg) {
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.flash.error")));
Assertions.assertTrue(driver.getPageSource().contains(msg));
}

}
================================================================
ALERTS PROGRAM ON HEROKUAPP WEBSITE:
Scenario:
1)Open the browser 
2)open the url :http://the-internet.herokuapp.com/
3)Verify the Page title and page heading
4)Click on JavaScript Alerts  link
5)Verify the JavaScript Alerts  Addressbar url and page heading
6)Click for Js Alert button
7)Handle Simple alert
8)Verify the Alert Result Text
9)Click for JS Confirm button
10)Handle Confirmation dialogbox 
11)click on confirmation dialogbox  Ok button
12)Verify the Alert Result Text for Ok button
13)Click for JS Confirm button again
14)Handle Confirmation dialogbox
15)click on confirmation dialogbox Cancel button
16)Verify the Alert Result Text for cancel
17)Click for JS Prompt button
18)Handle Prompt dialogbox 
19)type the value in editbox
20)Click on Prompt Ok button
21)Verify the Prompt Result Text for Ok button
22)Click for JS Prompt button again
23)Handle Prompt dialogbox
24)type the value in editbox 
25)click on prompt dialogbox Cancel button 
26)Verify the prompt Result Text for cancel
27)Close the browser
---------------------------------------------------------------------------------------
package junitprograms;

import static org.junit.jupiter.api.Assertions.*;

import java.time.Duration;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

class HerokuAppJSAlertsTest {
private static WebDriver driver = null;
private static WebDriverWait wait = null;

@BeforeAll
static void setUpBeforeClass() throws Exception {
// set the chromedriver.exe file path
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome971\\chromedriver_win32\\chromedriver.exe");
// interface refvar=new implementedclass();
driver = new ChromeDriver();

// maximize the window
driver.manage().window().maximize();

// add implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));

// open the url in browser
driver.get("http://the-internet.herokuapp.com/");

// create Object for WebDriverWait class
wait = new WebDriverWait(driver, Duration.ofMillis(30000));

wait.until(ExpectedConditions.titleContains("The Internet"));
// wait for the home page heading css=tagname.classvalue
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h1.heading")));
// fetch the header text
String headertxt = driver.findElement(By.cssSelector("h1.heading")).getText();
// assertEquals()
Assertions.assertEquals(headertxt, "Welcome to the-internet");
// assertTrue()
Assertions.assertTrue(driver.getPageSource().contains(headertxt));
// click on JavaScript Alerts
driver.findElement(By.linkText("JavaScript Alerts")).click();

}

@AfterAll
static void tearDownAfterClass() throws Exception {
if (driver != null) {
driver.quit();
}
}

@BeforeEach
void setUp() throws Exception {
// wait for the url
wait.until(ExpectedConditions.urlContains("http://the-internet.herokuapp.com/javascript_alerts"));
// wait for the page heading
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='example']/h3")));
// fetch teh header text Loginpage
String jsheadertxt = driver.findElement(By.cssSelector("div.example>h3")).getText();
// using assertEquals()
Assertions.assertEquals("JavaScript Alerts", jsheadertxt);
// using assertTrue()
Assertions.assertTrue(driver.getPageSource().contains(jsheadertxt));

}

@AfterEach
void tearDown() throws Exception {
// clear the cookies
driver.manage().deleteAllCookies();
}

@Test
void testSimpleAlert() {
System.out.println("started executing the testSimpleAlert()....");
// click on 'Click for JS Alert'
driver.findElement(By.xpath("//button[text()='Click for JS Alert']")).click();
// switch the focus to alert dialogbox
Alert alt = driver.switchTo().alert();
System.out.println("alert text is:" + alt.getText());
// close the simple alert
alt.accept();
verifyResultMessage("You successfully clicked an alert");
}

@Test
public void testConfirmationDialogbox() {
System.out.println("started executing the testConfirmationDialogbox()....");
// click on 'Click for JS Confirm'
driver.findElement(By.xpath("//button[text()='Click for JS Confirm']")).click();
// switch the focus to alert dialogbox
Alert cnf = driver.switchTo().alert();
System.out.println("alert text is:" + cnf.getText());
// click ok buttin in confirmation dialog
cnf.accept();
verifyResultMessage("You clicked: Ok");
// click on 'Click for JS Confirm'
driver.findElement(By.xpath("//button[text()='Click for JS Confirm']")).click();
// switch the focus to alert dialogbox
Alert cnf1 = driver.switchTo().alert();
System.out.println("alert text is:" + cnf1.getText());
// click cancel button in confirmation dialogt
cnf1.dismiss();
verifyResultMessage("You clicked: Cancel");
}

@Test
public void testPromptDialogbox() {
System.out.println("started executing the testPromptDialogbox()....");
// click on 'Click for JS Prompt'
driver.findElement(By.xpath("//button[text()='Click for JS Prompt']")).click();
// switch the focus to prompt alert dialogbox
Alert prmpt = driver.switchTo().alert();
System.out.println("alert text is:" + prmpt.getText());
// type the value in prompt editbox
prmpt.sendKeys("Selenium");

// click ok buttin in prompt dialog
prmpt.accept();
verifyResultMessage("You entered: Selenium");
// click on 'Click for JS Prompt'
driver.findElement(By.xpath("//button[text()='Click for JS Prompt']")).click();
// switch the focus to alert dialogbox
Alert prmpt1 = driver.switchTo().alert();
System.out.println("alert text is:" + prmpt1.getText());

prmpt1.sendKeys("webdriver");

// click cancel button in prompt dialogt
prmpt1.dismiss();
verifyResultMessage("You entered: null");

}

private void verifyResultMessage(String expmsg) {
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("p#result")));
String actMsg = driver.findElement(By.cssSelector("p#result")).getText();
System.out.println("alert result mesage is:" + actMsg);
Assertions.assertEquals(expmsg, actMsg);
}

}
=========================================================================
FRAMES PROGRAM ON HEROKUAPP WEBSITE:
SCENARIO:
1)Open the browser 
2)open the url :http://the-internet.herokuapp.com/
3)Verify the Page title and page heading
4)Click on Frames  link
5)Verify the Frames Addressbar url and page heading
6)Click on Nested Frames Link
7)Verify the Nested Frames page heading and URL
8)Fetch all the frames in the page
9)Switch to to frame and nested middle frame
10)Get the MIDDLE text and assert it
11)Navigate back to original position from frame
12Close the browser
-------------------------------------------------------------------------------------------------
package junitprograms;

import static org.junit.jupiter.api.Assertions.*;

import java.time.Duration;
import java.util.List;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

class HerokuAppFrameTest {
private static WebDriver driver = null;
private static WebDriverWait wait = null;

@BeforeAll
static void setUpBeforeClass() throws Exception {
// set the chromedriver.exe file path
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome971\\chromedriver_win32\\chromedriver.exe");
// interface refvar=new implementedclass();
driver = new ChromeDriver();

// maximize the window
driver.manage().window().maximize();

// add implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));

// open the url in browser
driver.get("http://the-internet.herokuapp.com/");

// create Object for WebDriverWait class
wait = new WebDriverWait(driver, Duration.ofMillis(30000));

wait.until(ExpectedConditions.titleContains("The Internet"));
// wait for the home page heading css=tagname.classvalue
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h1.heading")));
// fetch the header text
String headertxt = driver.findElement(By.cssSelector("h1.heading")).getText();
// assertEquals()
Assertions.assertEquals(headertxt, "Welcome to the-internet");
// assertTrue()
Assertions.assertTrue(driver.getPageSource().contains(headertxt));
// click on Frames l
driver.findElement(By.linkText("Frames")).click();
// wait for the url
wait.until(ExpectedConditions.urlContains("http://the-internet.herokuapp.com/frames"));
// wait for the page heading
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='example']/h3")));
// fetch teh header text Loginpage
String frmheadertxt = driver.findElement(By.cssSelector("div.example>h3")).getText();
// using assertEquals()
Assertions.assertEquals("Frames", frmheadertxt);
// using assertTrue()
Assertions.assertTrue(driver.getPageSource().contains(frmheadertxt));

}

@AfterAll
static void tearDownAfterClass() throws Exception {
if (driver != null) {
driver.quit();
}
}

@Test
void testFrames() {
System.out.println("started executing the testFrames()....");
// click on 'Nested Frames'
driver.findElement(By.partialLinkText("Nested Frames")).click();
//wait for the next page title:http://the-internet.herokuapp.com/nested_frames
wait.until(ExpectedConditions.urlToBe("http://the-internet.herokuapp.com/nested_frames"));
//fetch total number of frames
List<WebElement>framList=driver.findElements(By.tagName("frame"));
System.out.println("Number of frames in the page :"+framList.size());
/*//switch to top frame first then switch to child frame
switchToFrame("frame-top");
//fetch number of frames inside top frame
List<WebElement>topframList=driver.findElements(By.tagName("frame"));
System.out.println("Number of frames in the top frame page :"+topframList.size());
//switch to middle frame
switchToFrame("frame-middle");*/
switchToFrame("frame-top", "frame-middle");
//fetch the MIDDLE text
String txt=driver.findElement(By.id("content")).getText();
System.out.println("middle frame text is:"+txt);
Assertions.assertEquals("MIDDLE", txt);

}
/**
 * This method will switch to parent frame then to child frame
 * @param ParentFrame
 * @param ChildFrame
 */
private void switchToFrame(String ParentFrame, String ChildFrame) {
try {
driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);
System.out.println("Navigated to innerframe with id " + ChildFrame
+ "which is present on frame with id" + ParentFrame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + ParentFrame
+ " or " + ChildFrame + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to innerframe with id "
+ ChildFrame + "which is present on frame with id"
+ ParentFrame + e.getStackTrace());
}
}
/**
* this method will return from frame to original position
*/
private void switchtoDefaultFrame() {
try {
driver.switchTo().defaultContent();
System.out.println("Navigated back to webpage from frame");
} catch (Exception e) {
System.out
.println("unable to navigate back to main webpage from frame"
+ e.getStackTrace());
}
}
/**
* this method switch to given fame locator
* @param frame
*/
public void switchToFrame(String frame) {
try {
driver.switchTo().frame(frame);
System.out.println("Navigated to frame with name " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + frame
+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with id " + frame
+ e.getStackTrace());
}
}
}
=================================================================INTERNAL FRAMES PROGRAM
1)open http://jqueryui.com/
2)verify the page title.--jQuery UI
3)click on Autocomplete link under widgets section.
4)verify the page title.--Autocomplete | jQuery UI
5)switch to iframe 
6)type the tags value inn tags editbox
7)navigate back to previoius page
8)verify the page title
9)click on Accordion link.
10)verify the page title.--Accordion | jQuery UI

--------------------------------------------------------------------------------
package junitprograms;

import static org.junit.jupiter.api.Assertions.*;

import java.time.Duration;
import java.util.List;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

class JqueryIFrameTest {
private static WebDriver driver = null;
private static WebDriverWait wait = null;

@BeforeAll
static void setUpBeforeClass() throws Exception {
// set the chromedriver.exe file path
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome971\\chromedriver_win32\\chromedriver.exe");
// interface refvar=new implementedclass();
driver = new ChromeDriver();

// maximize the window
driver.manage().window().maximize();

// add implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));

// open the url in browser
driver.get("https://jqueryui.com/");

// create Object for WebDriverWait class
wait = new WebDriverWait(driver, Duration.ofMillis(30000));

wait.until(ExpectedConditions.titleContains("jQuery UI"));
// click on AutoComplete link
driver.findElement(By.linkText("Autocomplete")).click();
// wait for the url
wait.until(ExpectedConditions.urlContains("https://jqueryui.com/autocomplete/"));
//switch to iframe

}

@AfterAll
static void tearDownAfterClass() throws Exception {
if (driver != null) {
driver.quit();
}
}

@Test
void testIFrames() {
System.out.println("started executing the testIFrames()....");
//fetch total number of frames
List<WebElement>iframList=driver.findElements(By.tagName("iframe"));
System.out.println("Number of iframes in the page :"+iframList.size());
WebElement ifrmele=driver.findElement(By.className("demo-frame"));
//switch to iframe element
switchToFrame(ifrmele);
//type the value tags editbox
driver.findElement(By.id("tags")).sendKeys("webdriver");
//switch back to jqueryui home page
driver.navigate().back();
wait.until(ExpectedConditions.titleIs("jQuery UI"));

}
/**
 * This method will switch to parent frame then to child frame
 * @param ParentFrame
 * @param ChildFrame
 */
private void switchToFrame(String ParentFrame, String ChildFrame) {
try {
driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);
System.out.println("Navigated to innerframe with id " + ChildFrame
+ "which is present on frame with id" + ParentFrame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + ParentFrame
+ " or " + ChildFrame + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to innerframe with id "
+ ChildFrame + "which is present on frame with id"
+ ParentFrame + e.getStackTrace());
}
}
/**
* this method will return from frame to original position
*/
private void switchtoDefaultFrame() {
try {
driver.switchTo().defaultContent();
System.out.println("Navigated back to webpage from frame");
} catch (Exception e) {
System.out
.println("unable to navigate back to main webpage from frame"
+ e.getStackTrace());
}
}
/**
* this method switch to given fame locator
* @param frame
*/
public void switchToFrame(String frame) {
try {
driver.switchTo().frame(frame);
System.out.println("Navigated to frame with name " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + frame
+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with id " + frame
+ e.getStackTrace());
}
}
public void switchToFrame(WebElement frameElement) {
try {
if (frameElement.isDisplayed()) {
driver.switchTo().frame(frameElement);
System.out.println("Navigated to frame with element "+ frameElement);
} else {
System.out.println("Unable to navigate to frame with element "+ frameElement);
}
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with element " + frameElement + e.getStackTrace());
} catch (StaleElementReferenceException e) {
System.out.println("Element with " + frameElement + "is not attached to the page document" + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with element " + frameElement + e.getStackTrace());
}
}
}

=================================================================================================

Junit FrameWork

Junit Framework:Its java unit testing framework.maily used for unit testing purpose.
Latest version of Junit is:jupitor junit (junit 5)

Annotation:it provides metadata to the classes and methods.Annotation starts with symbol @ followed by name.

Junit 5 is the latest version --that name is Jupiter Junit

Annotations:
Junit 4          Jupiter Junit
@BeforeClass or @BeforeAll
@Before  or    @BeforeEach
@Test @Test
@After         @AfterEach
@AfterClass    @AfterAll
@Ignore        @Disabled
@Runwith       @Runwith
@Suite         @Suite


@BeforeClass:first this block of code will execute only once before executing any test method
only precondition steps for test method should be written inside this block
Syntax:
@BeforeClass/@BeforeAll
public static void methodName(){

//precondition code

}
@Before:this annotated method will execute before every test method

@Before/@BeforeEach
public void setUp(){
//write the code
}
@Test:only test steps should be written inside this method
we can write more than one @Test annotations in junit/testNG class.

@Test
public void testMethodName(){
//only test steps

}
@Test
public void test2(){test steps code}

Note:you can write multiple @Test annotations but method name must be different

@After:this annotated method will be executed after each test method

@After/@AfterEach
public void tearDown(){
//destroycode
}
@AfterClass:this annotated method will be executed after all the test methods of the class

@AfterClass/@AfterAll
public static void afterClass(){
//destroycode
}

@Ignore:if you want to ignore the execution of any test method, just write @Ignore above the @Test annotation

@Ignore
@Test
public void test1(){}

Execution order

@BeforeClass/@BeforeAll
.
.
.
@Before/@BeforeEach
.
.
@Test
.
.
@After/@AfterEach
.
.
@Before(if one more test method is there)/@BeforeEach
.
.
@Test(2nd test method)
.
.
@After/@AfterEach
.
.
@AfterClass/@AfterAll

Features :

  •  JUnit is an open source framework which is used for writing & running tests.
  •  Provides Annotation to identify the test methods.
  •  Provides Assertions for testing expected results.
  •  Provides Test runners for running tests.
  •  JUnit tests allow you to write code faster which increasing quality
  •  JUnit is elegantly simple. It is less complex & takes less time.
  •  JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results. 
  •  JUnit tests can be organized into test suites containing test cases and even other test suites.
  •  Junit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
  • The @Category annotation has been replaced by the @Tag annotation.
  • JUnit 5 adds a new set of assertion methods.
  • Runners have been replaced with extensions, with a new API for extension implementors.
  • JUnit 5 introduces assumptions that stop a test from executing.
  • JUnit 5 supports nested and dynamic test classes.
====================================================================

The Assertions class and its methods

The org.junit.jupiter.api.Test annotation denotes a test method. Note that the @Test annotation now comes from the JUnit 5 Jupiter API package instead of JUnit 4's org.junit package. The testConvertToDecimalSuccess method first executes the MathTools::convertToDecimal method with a numerator of 3 and a denominator of 4, then asserts that the result is equal to 0.75. The org.junit.jupiter.api.Assertions class provides a set of static methods for comparing actual and expected results. The Assertions class has the following methods, which cover most of the primitive data types:
  • assertArrayEquals compares the contents of an actual array to an expected array.
  • assertEquals compares an actual value to an expected value.
  • assertNotEquals compares two values to validate that they are not equal.
  • assertTrue validates that the provided value is true.
  • assertFalse validates that the provided value is false.
  • assertLinesMatch compares two lists of Strings.
  • assertNull validates that the provided value is null.
  • assertNotNull validates that the provided value is not null.
  • assertSame validates that two values reference the same object.
  • assertNotSame validates that two values do not reference the same object.
  • assertThrows validates that the execution of a method throws an expected exception (you can see this in the testConvertToDecimalInvalidDenominator example above).
  • assertTimeout validates that a supplied function completes within a specified timeout.
  • assertTimeoutPreemptively validates that a supplied function completes within a specified timeout, but once the timeout is reached it kills the function's execution.
 --------------------------------------------------------------------------------------------------------------------

Running your unit test

In order to run JUnit 5 tests from a Maven project, you need to include the maven-surefire-plugin in the Maven pom.xml file and add a new dependency. Listing 3 shows the pom.xml file for this project.

Listing 3. Maven pom.xml for an example JUnit 5 project


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.javaworld.geekcap</groupId>
      <artifactId>junit5</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <build>
          <plugins>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>3.8.1</version>
                  <configuration>
                      <source>8</source>
                      <target>8</target>
                  </configuration>
              </plugin>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-surefire-plugin</artifactId>
                  <version>3.0.0-M4</version>
              </plugin>
          </plugins>
      </build>
      <name>junit5</name>
      <url>http://maven.apache.org</url>
      <dependencies>
          <dependency>
              <groupId>org.junit.jupiter</groupId>
              <artifactId>junit-jupiter</artifactId>
              <version>5.6.0</version>
              <scope>test</scope>
          </dependency>
      </dependencies>
  </project>

JUnit 5 dependencies

JUnit 5 packages its components in the org.junit.jupiter group and we need to add the junit-jupiter artifact, which is an aggregator artifact that imports the following dependencies:
  • junit-jupiter-api defines the API for writing tests and extensions.
  • junit-jupiter-engine is the test engine implementation that runs the unit tests.
  • junit-jupiter-params provides support for parameterized tests.
Next, we need to add the maven-surefire-plugin build plug-in in order to run the tests.
Finally, be sure to include the maven-compiler-plugin with a version of Java 8 or later, so that you'll be able to use Java 8 features like lambdas.

Run it!

Use the following command to run the test class from your IDE or from Maven:
mvn clean test
If you're successful, you should see output similar to the following:

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.javaworld.geekcap.math.MathToolsTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.04 s - in com.javaworld.geekcap.math.MathToolsTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.832 s
[INFO] Finished at: 2020-02-16T08:21:15-05:00
[INFO] ------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------

New in JUnit 5: Tags

Before wrapping up this introduction to the core of JUnit 5, I'll show you how to use tags to selectively run different test cases in different scenarios. Tags are used to identify and filter specific tests that you want to run in different scenarios. For example, you can tag a test class or a test method as an integration test and another as development. The names and uses of the tags are all up to you.
We'll create three new test classes and tag two of them as development and one as production, presumably to differentiate between tests you want to run when building for different environments

Listing 6. Tags, Test 1 (TestOne.java)


package com.javaworld.geekcap.tags;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("Development")
class TestOne {
    @Test
    void testOne() {
        System.out.println("Test 1");
    }
}

Listing 7. Tags, Test 2 (TestTwo.java)


package com.javaworld.geekcap.tags;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("Development")
class TestTwo {
    @Test
    void testTwo() {
        System.out.println("Test 2");
    }
}

Listing 8. Tags, Test 3 (TestThree.java)

package com.javaworld.geekcap.tags;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("Production")
class TestThree {
    @Test
    void testThree() {
        System.out.println("Test 3");
    }
}
Tags are implemented through annotations, and you can annotate either an entire test class or individual methods in a test class; furthermore, a class or a method can have multiple tags. In this example, TestOne and TestTwo are annotated with the "Development" tag, and TestThree is annotated with the "Production" tag. We can filter test runs in different ways based on tags. The simplest of these is to specify a test in your Maven command line; for example, the following only executes tests tagged as "Development":
mvn clean test -Dgroups="Development"
The groups property allows you to specify a comma-separated list of tag names for the tests that you want JUnit 5 to run. Executing this yields the following output:
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.javaworld.geekcap.tags.TestOne
Test 1
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 s - in com.javaworld.geekcap.tags.TestOne
[INFO] Running com.javaworld.geekcap.tags.TestTwo
Test 2
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 s - in com.javaworld.geekcap.tags.TestTwo
Likewise, we could execute just the "Production" tests as follows:
mvn clean test -Dgroups="Production"
Or both "Development" and "Production" as follows:
mvn clean test -Dgroups="Development, Production"
Test suite Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
example:
@RunWith(Suite.class)
@Suite.SuiteClasses({ TestJunit1.class ,TestJunit2.class })


Limitations of Junit:
1)dependent testcases cannot be executed
2)you cannot prioritize the test cases
3)you dont have an option to do datadriven testing with an annotation.