How to install TestNG in eclipse
Once installed then restart eclipse.
Lets create a TestNG project
File > New > Java Project > Provide some name and click finish
Create a class as TestNGClass
Create following class
1.LoginPage.class
2.HomePage.class
3.FBLoginTest.class
Here goes the code:
LoginPage class
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage {
@FindBy(id = "email")
private WebElement username;
@FindBy(id = "pass")
private WebElement password;
@FindBy(xpath = ".//input[@data-testid='royal_login_button']")
private WebElement login;
WebDriver driver;
public LoginPage(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void enterUserName(String name){
username.clear();
username.sendKeys(name);
}
public void enterPassword(String passwrd){
password.clear();
password.sendKeys(passwrd);
}
public HomePage clickLoginButton(){
login.click();
return new HomePage(driver);
}
}
HomePage class.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class HomePage {
@FindBy(id = "userNavigationLabel")
private WebElement userDropdown;
WebDriver driver;
public HomePage(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
}
public boolean isUserLoggedIn(){
return userDropdown.isDisplayed();
}
}
FBLoginTest class
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import com.testng.pages.HomePage;
import com.testng.pages.LoginPage;
public class FBLoginTest {
WebDriver driver;
LoginPage loginPage;
HomePage homePage;
@BeforeClass
public void openFBPage(){
driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
loginPage = new LoginPage(driver);
}
@Test
public void loginToFB(){
loginPage.enterUserName("");
loginPage.enterPassword("");
homePage = loginPage.clickLoginButton();
Assert.assertTrue(homePage.isUserLoggedIn());
}
@AfterClass
public void closeBrowser(){
driver.quit();
}
}
Here comes the testng xml: Right click on Project create a xml file and copy paste this content.
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite">
<test name="Test">
<classes>
<class name="com.testng.FBLoginTest"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
How to add selenium standalone jar:
Download the latest selenium standalone jar & Add that in the Project's Build path.
How to run the TestNG xml? Right click on the xml > Run as > TestNGSuite
Happy Coding :)