I have tried this following code to automate gmail,in the first function the browser is able to get the element till "Compose" and click on it but the next few elements like "to" , "subject" is not found ..i have specified the next elements in void mailSend() function , i am not sure why it does not read the next elements.
public class Example{
public static WebDriver driver;
#BeforeClass
public void before()
{
driver = new FirefoxDriver();
}
#Test(dataProvider = "Data-Provider-Function")
public void startup(String uName,String pass) throws Exception
{
driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys(uName);
driver.findElement(By.id("Passwd")).sendKeys(pass);
driver.findElement(By.id("signIn")).click();
Thread.sleep(4000);
driver.findElement(By.cssSelector("div[class='T-I J-J5-Ji T-I-" +
"KE L3']")).click();
Thread.sleep(4000);
}
#DataProvider (name = "Data-Provider-Function")
public Object[][] startupProvider()
{
return new Object[][]
{
{"selva.prokarma.test#gmail.com", "prokarma"}
};
}
#Test(dataProvider="Mail Information")
public void mailSend(String to,String subject,String body) throws Exception
{
driver.navigate().refresh();
Thread.sleep(2000);
driver.findElement(By.className("vO")).sendKeys(to);
Thread.sleep(2000);
driver.findElement(By.className("aoT")).sendKeys(subject);
Thread.sleep(2000);
driver.findElement(By.cssSelector(".editable")).click();
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(#tabindex,'1') and contains(#frameborder,'0')]")));
driver.findElement(By.xpath("//body[#role='textbox']")).sendKeys(body);
driver.switchTo().defaultContent();
driver.findElement(By.cssSelector("div[class='T-I J-J5-Ji aoO T-I-atl L3']")).click();
Thread.sleep(4000);
driver.navigate().refresh();
Thread.sleep(4000);
}
#DataProvider (name = "Mail Information")
public Object[][] mailSendProvider()
{
return new Object[][]
{
{"selva.prokarma.test#gmail.com", "This is a Test Mail","Prokarma"},
{"selva.prokarma.test#gmail.com", "This is Test Mail 2","Hello Automation King "},
{"selva.prokarma.test#gmail.com","This is another Test Mail 3","Hello Selva"},
{"selva.prokarma.test#gmail.com","This is another Test Mail 3","Hello SelvaKumar"},
{"selva.prokarma.test#gmail.com","Hi How are you doing","Robotium Tasks to be followed"}
};
}
#AfterClass
public void tear()
{
driver.quit();
}
}
I kept the wait as 60 secs and removed all sleep statements which are not at all required. and More over i tried everything in single test method.
public class Example2 {
public static WebDriver driver;
#BeforeClass
public void before()
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60000, TimeUnit.MILLISECONDS);
}
#Test(dataProvider="Mail Information")
public void mailSend(String to,String subject,String body) throws Exception
{
driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys("xyzy#gmail.com");
driver.findElement(By.id("Passwd")).sendKeys("*********");
driver.findElement(By.id("signIn")).click();
driver.findElement(By.cssSelector("div[class='T-I J-J5-Ji T-I-KE L3']")).click();
driver.findElement(By.className("vO")).sendKeys(to);
driver.findElement(By.className("aoT")).sendKeys(subject);
driver.findElement(By.cssSelector(".editable")).click();
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(#tabindex,'1') and contains(#frameborder,'0')]")));
driver.findElement(By.xpath("//body[#role='textbox']")).sendKeys(body);
driver.switchTo().defaultContent();
driver.findElement(By.cssSelector("div[class='T-I J-J5-Ji aoO T-I-atl L3']")).click();
driver.navigate().refresh();
}
#DataProvider (name = "Mail Information")
public Object[][] mailSendProvider()
{
return new Object[][]
{
{"xyzy#gmail.com", "This is a Test Mail","hello"},
};
}
#AfterClass
public void tear()
{
driver.quit();
}
Attaching the output screenshot as well...
Related
I did a basic project to training about Page Objects using selenium WebDriver with java and Junit. So, I make a page object class and Junit class too. I Make a call of method and pass the parameters to method but, the eclipse show a message that say: java.lang.NullPointerException
public class LogarBkoMaisPage {
static WebDriver driver;
By campoNome = By.id("matricula_I");
By campoSenha = By.id("senha_I");
By btnLogin = By.id("bt_entrar");
public LogarBkoMaisPage(WebDriver driver) {
this.driver = driver;
}
public void logar(String usuario, String senha) {
driver.findElement(campoNome).sendKeys(usuario);
driver.findElement(campoSenha).sendKeys(senha);
driver.findElement(btnLogin).click();
}
}
public class LogarBkoMaisTest {
static WebDriver driver;
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
nav.iniciarNavegador("ie","http://10.5.9.45/BkoMais_Selenium/");
}
#Test
public void logarAplicacao() {
try {
LogarBkoMaisPage login = new LogarBkoMaisPage(driver);
login.logar("844502","Bcc201707");
}catch(Exception e) {
System.out.println("Mensagem de erro: " +e);
}
}
#After
public void tearDown() throws Exception {
}
}
public class SelecionarNavegador {
static WebDriver driver;
public static WebDriver iniciarNavegador(String nomeNavegador, String url) {
if(nomeNavegador.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "E:\\workspace_BCC_QA_BKOMAIS\\"
+ "FireFoxGeckodriver64\\geckodriver.exe");
driver = new FirefoxDriver();
}
else if(nomeNavegador.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "E:\\workspace_BCC_QA_BKOMAIS"
+ "\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}else if(nomeNavegador.equalsIgnoreCase("IE")) {
System.setProperty("webdriver.ie.driver", "E:\\workspace_BCC_QA_BKOMAIS"
+ "\\IE Plugin\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
Exception:
You are getting a null pointer exception because iniciarNavegador method inside SelecionarNavegador class is the one which initializes the driver and it returns the driver which has to be assigned to a vairable. You need to do this in your setUp()method
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
driver=nav.iniciarNavegador("ie","http://10.5.9.45/BkoMais_Selenium/");
}
I am stuck in a scenario, where user is allowed to rate the movie only once a day with same user credentials.
If user tried to rate the same movie or contract, error pop_up seen.
I want to Implement in a way, that if once any movie/contract is rated. The rating functionality should be skipped and Error pop should be Handled.
I am using Selenium eclipse 2017, Chrome browser 61.0 and Test-Ng
Please help in the same.
Thanks.
public class Ratings {
String driverPath = "F:/ChromeDriver/chromedriver.exe";
public WebDriver driver;
public Alert alert;
#BeforeTest
public void LaunchBrowser () throws InterruptedException {
System.out.println("WebBrowser open");
System.setProperty("webdriver.chrome.driver","F:/ChromeDriver/chromedriver.e
xe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
#Test (priority = 1, alwaysRun = true)
public void HomePageUSA() throws InterruptedException {
driver.navigate().to("Https://us.justdial.com");
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
AssertJUnit.assertEquals(expectedTitle, actualTitle);
System.out.println("Test Passed");
}
catch (Throwable e)
{
System.out.println("Test Failed");
}
Thread.sleep(3000);
}
#Test (priority = 2, dependsOnMethods = {"HomePageUSA"})
public void Login() throws Exception{
Thread.sleep(3000);
driver.findElement(By.xpath("/html/body/div/div[1]/div[1]/div[1]/div/div/div
/div[4]/aside/div/span/a[1]")).click();
driver.findElement(By.id("inputPassword3")).clear();
driver.findElement(By.id("inputPassword3")).sendKeys("testing.testjd#gmail.c
om");
driver.findElement(By.id("exampleInputPassword1")).clear();
driver.findElement(By.id("exampleInputPassword1")).sendKeys("justdial");
driver.findElement(By.xpath("/html/body/div[4]/div[2]/div[1]/section/div/div
[1]/div/form/div[3]/div/button")).click();
Thread.sleep(1000);
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
Assert.assertEquals(expectedTitle, actualTitle);
System.out.println("Login Successful");
}
catch (Throwable e)
{
System.out.println("Login Failed");
}
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div[1]/div/header/div/div[1]/a[2]")).click();
Thread.sleep(2000);
}
#Test (priority = 3)
public void Movies_Rating_page() throws Exception {
driver.findElement(By.xpath(".//*[#id='hotkeylnk106']/div[2]")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[3]/div[2]/div/div[1]/div[1]/div/a/span/img")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[2]/div[1]/ul/li[2]/span/a[2]/span[1]")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(".//*
[#id='AlreadyRated']/div/div/div/section/div/a")).click();
System.out.println("Rating Page Redirection Successful");
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[2]/span[2]/span[10]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[3]/textarea")).sendKeys("Very nice
movie, Must watch.");
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[4]/button[2]")).click();
Thread.sleep(3000);
System.out.println("Rating Successfully Submitted");
You can create a method and tag that method in your test method as dependsOnMethods . You can achieve it like below (i tried to answer to the best based on the info provided)
The idea here is that when your rated condition is met isMovieRated should throw exception so that Movies_Rating_page() will be skipped by testNG ,otherwise isMovieRated just returns true and nothing should be skip.
#Test
public static boolean isMovieRated(String locator) {
//check in "if" below that element has already clicked or is equal to something. I used 'AlreadyClicked' just to
give an idea as I dont have your application information.
if (driver.findElement(By.xpath(locator).getText()=="AlreadyClicked"){
throw new RuntimeException();
}
else {
return true;
}
}
Now your Movies_Rating_page() will look like this
#Test (priority = 3,dependsOnMethods = { "isMovieRated" })
public void Movies_Rating_page() throws Exception {
public static String YourLocator = "/html/body/...."
Ratings.isMovieRated(YourLocator);
..
}
here is a link for more info on testNG dependsOnMethods
Note:
The code above is not tested.
If you are doing things other than checking rating in Movies_Rating_page() then you should separate those things because everything will be skipped when an exception is thrown.
Hope this helps.
My coding not find element. Pls anyone help me to come out of my mistake.
Testcase
#Test
public void main() throws Exception {
Thread.sleep(5000);
System.out.println("Before sign in action execution");
SignIn_Action.Execute(iTestCaseRow);
}
SignIn_Action
public class SignIn_Action{
public static void Execute(int iTestCaseRow) throws Exception{
// Fetch user name from Excel
String sUserName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_UserName);
System.out.println("User Name read from --> "+ sUserName);
// Fetch password from Excel
String sPassword = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Password);
System.out.println("Password read from excel --> "+ sPassword);
LoginPageObjects.txtbx_username().sendKeys(sUserName);
LoginPageObjects.txtbx_password().sendKeys(sPassword);
LoginPageObjects.btn_login().click();
}
LoginPageObject class
public class LoginPageObjects extends BaseClass {
private static WebElement element = null;
public LoginPageObjects(WebDriver driver){
super(driver);
}
public static WebElement txtbx_username(){
try {
WebElement element = null;
System.out.println("Inside txtbx_username method");
element = driver.findElement(By.name("first_name"));
System.out.println("Fetched element name is : "+element);
Log.info("Username text box found");
}catch (Exception e){
Log.error("UserName text box is not found on the Login Page");
throw(e);
}
return element;
}
}
}
BaseClass
public class BaseClass {
public static WebDriver driver;
public static boolean bResult;
public BaseClass(WebDriver driver){
BaseClass.driver = driver;
BaseClass.bResult = true;
}
}
My problem is in the below code
element = driver.findElement(By.name("first_name"));
This code is not find element and it shows below error message
java.lang.NullPointerException
at pageObjects.LoginPageObjects.txtbx_username(LoginPageObjects.java:27)
I am getting "java.lang.NullPointerException" when I am trying to execute my test case based on POM.
The class BrowserFactory lets me choose a browser, the class Flipkart_Login based on POM stores all the element of that particular page and has a method for Valid_Login()
and finally Test_Flipkart_Login class - calls the Valid_Login() method for executon but when I try to execute this class, I get java.lang.NullPointerException.
Kindly advise!
FAILED: Flipkart_Login_Test
java.lang.NullPointerException
at DataProviders.ConfigDataProvider.getURL(ConfigDataProvider.java:31)
at TestCases.Test_Flipkart_Login.Flipkart_Login_Test(Test_Flipkart_Login.java:19)
public class ConfigDataProvider
{
static Properties pro;
public ConfigDataProvider()
{
File src = new File("C:\\Data\\Bimlesh\\Flipkart_HybridFramework\\Flipkart.Hybrid.FrameworkComplete\\Configuration\\Config.Properties");
try
{
FileInputStream fis = new FileInputStream(src);
pro = new Properties();
pro.load(fis);
} catch (Exception e)
{
System.out.println("The Config exception is :"+e.getMessage());
}
}
public static String getURL()
{
String URL = pro.getProperty("URL");
return URL;
}
public static String ChromePath()
{
String Chrome = pro.getProperty("Chromepath");
return Chrome;
}
public static String IEPath()
{
String IE = pro.getProperty("IEpath");
return IE;
}
}
public class BrowserFactory
{
static WebDriver driver;
public static WebDriver getBrowser(String BrowserName)
{
if(BrowserName.equalsIgnoreCase("Firefox"))
{
driver = new FirefoxDriver();
}
else if(BrowserName.equalsIgnoreCase("Chrome"))
{
System.setProperty("webdriver.chrome.driver", ConfigDataProvider.ChromePath());
driver = new ChromeDriver();
}
else if(BrowserName.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver", ConfigDataProvider.IEPath());
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
return driver;
}
public void ShutDown(WebDriver driver)
{
driver.quit();
}
}
public class Flipkart_Login
{
WebDriver driver;
public Flipkart_Login(WebDriver driver)
{
this.driver=driver;
}
#FindBy(xpath="//a[text()='Log In']") WebElement Login_Click;
#FindBy(xpath="//input[#class='_2zrpKA' and #type='text']") WebElement Enter_Email;
#FindBy(xpath="//input[#class='_2zrpKA _3v41xv' and #type='password']") WebElement Enter_Pass;
#FindBy(xpath="//button[#type='submit' and #class='_3zLR9i _1LctnI _36SmAs']") WebElement Login_Button;
public void Valid_Login()
{
Login_Click.click();
Enter_Email.sendKeys("xxx#gmail.com");
Enter_Pass.sendKeys("xxx");
Login_Button.click();
}
}
public class Test_Flipkart_Login
{
WebDriver driver;
#Test
public void Flipkart_Login_Test()
{
driver = BrowserFactory.getBrowser("Firefox");
driver.get(ConfigDataProvider.getURL());
Flipkart_Login page1 = PageFactory.initElements(driver, Flipkart_Login.class);
page1.Valid_Login();
}
}
You have initialized Properties pro in the constructor of the COnfigDataProider but you are using a static call to getURL method from your test class. Thus pro will be null and not initialized. Remove static call and use the constructor or make pro to static and initialize in static block.
I am trying to do following :
Go to yelp.com
Select “Restaurants” after clcking in the drop-down box in Find
I am not able to click on "Restaurants" as xpath is not able to locate element.
I checked with selenium-webdriver, junit. Below code is working fine for me. Check this resolves for you.
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
baseUrl = "http://www.yelp.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testYelpRest() throws Exception {
driver.get(baseUrl + "");
driver.findElement(By.id("find_desc")).clear();
driver.findElement(By.id("find_desc")).sendKeys("Restaurants");
driver.findElement(By.id("find_desc")).sendKeys(Keys.DOWN);
driver.findElement(By.id("find_desc")).sendKeys(Keys.ENTER);
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.xpath("//span[#class='pagination-results-window']"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
you can try below code, i m sure it will work..:)
public class Yelp_dropdown {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.yelp.com/");
WebDriverWait w= new WebDriverWait(driver,5);
driver.findElement(By.xpath(".//*[#id='find_desc']")).click();
w.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[#class='suggestion-detail suggestion-name' and contains (text(), 'Restaurants')]"))).click();