Sunday, May 10, 2020

TestNG Assertion in Selenium WebDriver with Java

Test Scenario/Steps:

1. Open a browser (in my case Firefox)
2. Navigate to test URL say https://link.testproject.io/bsg
3. Assert the title of page
4. Click Login link at the top right corner
5. Enter invalid Username & Email --> Click Sign in button
6. Login will fail and a notification message will be displayed --> Assert the validation message

The following is the complete Selenium java code using TestNG framework:

package assertion_verification;

import java.util.ArrayList;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

public class ValidationOfInvalidLogin_TestNG {
private WebDriver driver;
JavascriptExecutor js;
String baseURL;
@BeforeClass
public void setUp() {
System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\" + "src\\test\\resources\\Driver\\geckodriver-v0.24.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
js = (JavascriptExecutor) driver;
baseURL = "https://link.testproject.io/bsg";
}
@AfterClass
public void tearDown() {
driver.quit();
}

@Test
public void validationOfInvalidLogin() throws Exception{
//Open test URL: https://link.testproject.io/bsg
driver.get(baseURL);
Thread.sleep(3000);
//assertion of title of page using TestNG
String actualTitle = driver.getTitle();
String expectedTitle = "Free Test Automation For All – TestProject";
assertEquals(expectedTitle,actualTitle);
//OR,
assertTrue(actualTitle.contains(expectedTitle));

String parentWindowHandle = driver.getWindowHandle();
driver.findElement(By.linkText("Login")).click();
Thread.sleep(3000);

ArrayList<String> windowHandles = new ArrayList<String>(driver.getWindowHandles());
for (String window:windowHandles){
if (window != parentWindowHandle){
driver.switchTo().window(window);
}
}
Thread.sleep(3000);

driver.findElement(By.name("username")).clear();
driver.findElement(By.name("username")).sendKeys("fff@gmail.com");

driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("1234567890");
//Click Signin button
driver.findElement(By.id("tp-sign-in")).click();
//Assertion of notification message with TestNG
String actualMsg = driver.findElement(By.id("tp-message-error")).getText();
String expectedMsg = "Invalid username or password.";
assertEquals(expectedMsg,actualMsg);
}
}

No comments:

Post a Comment