Use Assertion in Selenium TestNG
package asc;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class VerifyTitle {
@Test
public void titleTest() {
String expectedTitle = "Electronics, Cars, Fashion, Collectibles & More | eBay";
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.ebay.com/");
String actualtitle = driver.getTitle();
System.out.println(actualtitle);
Assert.assertEquals(actualtitle, expectedTitle);
driver.close();
}
}
Package and Imports
package asc;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
- package asc;: Declares the package name 'asc' for this class.
- import org.openqa.selenium.chrome.ChromeDriver;: Imports the ChromeDriver class from Selenium, which is used to control Google Chrome.
- import org.testng.Assert;: Imports the Assert class from TestNG, which is used to perform assertions in tests.
- import org.testng.annotations.Test;: Imports the Test annotation from TestNG, used to denote a method as a test method.
- import io.github.bonigarcia.wdm.WebDriverManager;: Imports WebDriverManager, a utility to automatically manage (download and configure) WebDriver binaries like chromedriver.
Test Class and Method
public class VerifyTitle {
@Test
public void titleTest() {
String expectedTitle = "Electronics, Cars, Fashion, Collectibles & More | eBay";
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.ebay.com/");
String actualtitle = driver.getTitle();
System.out.println(actualtitle);
Assert.assertEquals(actualtitle, expectedTitle);
driver.close();
}
}
Explanation:
- Class Definition:
- public class VerifyTitle: Defines a public class named VerifyTitle.
- Test Method:
- @Test: The titleTest method is annotated with @Test, indicating that it is a TestNG test method.
- Expected Title:
- String expectedTitle = " Electronics, Cars, Fashion, Collectibles & More | eBay ";: This string holds the expected title of the eBay homepage.
- Setting Up WebDriver:
- Creating WebDriver Instance:
- Navigating to URL:
- Getting the Actual Title:
- Printing the Actual Title:
- Assertion:
- Closing the Browser:
-
driver.close();:
This closes the browser after the test is completed.