can someone teach me how to use property file for a simple login application - selenium

can someone help me with using property file for a sample login application? this helps in achieving me for another big automation.
I have given objects in objects.propreties
in main java class how shall i proceed with?
package valuescompare;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class practice {
public static FileInputStream fis;
public static String propertyfilepath="E:\\Ashik\\wkspSelenium\\valuescompare\\src\\valuescompare\\object.properties";
public static String getProperty(String key) throws IOException, FileNotFoundException{
fis=new FileInputStream(propertyfilepath);
Properties prop=new Properties();
prop.load(fis);
return prop.getProperty(key);
}
static WebDriver driver=new FirefoxDriver();
public static void openBrowser() throws FileNotFoundException, IOException {
//public WebDriver driver;
driver.get(getProperty("url"));
//maximizes the window
driver.manage().window().maximize();
Wait(1000);
}
public static void login() throws FileNotFoundException, IOException{
driver.findElement(By.xpath(getProperty("uidxpath"))).sendKeys(getProperty("uid"));
driver.findElement(By.xpath(getProperty("pwdxpath"))).sendKeys(getProperty("pwd"));
driver.findElement(By.xpath(getProperty("submit"))).click();
Wait(5000);
}
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
/*practice prac=new practice();
prac.openBrowser();
prac.login(); */
openBrowser();
login();
}
public static void Wait(int time){
try {
Thread.sleep(time);
} catch (Exception e) {
// TODO: handle exception
}
}
}

Say you create a 'config.properties' named file somewhat like this :
userName=admin
password=admin
and say you are using Java as your programming language, then you have to use it in this manner:
Properties properties = new Properties();
properties.load(new FileInputStream("Config.properties"));
String uName = properties.getProperty("userName");
String pwd = properties.getProperty("password");
Now you have got the values fetched from properties file, use it wherever required.
For more info you may refer this link: http://www.mkyong.com/java/java-properties-file-examples/

Related

Selenium - Use text string in several TestNG #Test-annotations

I have a text string tag i grab with getText.
Then i want to use that string in another #Test
I have tried to put it in #BeforeSuite but can't make that to work either?
Can you please assist...:)
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class values_test {
static WebDriver driver;
#BeforeTest
public void setup() throws Exception {
driver = new HandelDriver().getDriver("CHROME");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://chercher.tech/selenium-webdriver-sample");
}
#Test (priority = 100)
public void GetText() throws IOException {
// fetches text from the element and stores it in text
String text = driver.findElement(By.xpath("//li[#class='breadcrumb-item active update']")).getText();
System.out.println("Text String is : "+ text);
}
#Test (priority = 101)
public void PasteText() throws IOException {
driver.findElement(By.xpath("//input[#id=\"exampleInputEmail1\"]")).sendKeys(text);
}
#AfterTest
public void afterTest() {
driver.close();
}
}
It seems that your GetText() method actually is not a test method, but a utility method. It can be a part of another package, but certainly does need to have a #Test annotation. You can still call it's logic in the BeforeTest method.
Either way, if you want to use this string in multiple tests, you need a reference to it, i.e. the value_test class should have a String text field. I would also advise using a more descriptive variable name than "text".
You can still call it in the BeforeTest set up, but now you'll have where to store the fetched value.
Along the lines of:
public class values_test {
static WebDriver driver;
static String text;
#BeforeTest
public void setup() throws Exception {
driver = new HandelDriver().getDriver("CHROME");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://chercher.tech/selenium-webdriver-sample");
GetText();
}
public void GetText() throws IOException {
text = driver.findElement(By.xpath("//li[#class='breadcrumb-item active update']")).getText();
System.out.println("Text String is : "+ text);
}
#Test (priority = 101)
public void CanPasteTextInFirstEmailField() throws IOException {
driver.findElement(By.xpath("//input[#id=\"exampleInputEmail1\"]")).sendKeys(text);
}
#Test (priority = 102)
public void CanPasteTextInSecondEmailField() throws IOException {
driver.findElement(By.xpath("//input[#id=\"exampleInputEmail2\"]")).sendKeys(text);
}
PS Each test should have a clear outcome, so you unequivocally know the results of a test case. Be sure to read up on Asserts, TestNG offers loads of possibilities.
PPS The names of tests should also be more descriptive and should de really precise on what it is testing.

NullPointerException in my code. How to deal with it

I've written my code in Java using Selenium. When I run the code, it's throwing a NullPointerException. Check the exception below
Exception in thread "main" java.lang.NullPointerException
at AdminInterface.loginApplication(AdminInterface.java:17)
at AdminInterface.main(AdminInterface.java:29)
My code is as follows:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class AdminInterface {
public WebDriver driver;
public void launchApplication() throws Exception
{
System.setProperty("webdriver.ie.driver", "C:\\Users\\rprem\\Downloads\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://www.gcrit.com/build3/admin/");
}
public void loginApplication(String Username, String Password)
{
driver.findElement(By.name("username")).sendKeys(Username);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.id("tbd1")).click();
}
public void closeBrowser()
{
driver.close();
}
public static void main(String[] args)
{
AdminInterface obj = new AdminInterface();
obj.loginApplication("admin", "admin#123");
}
}
You are seeing a NullPointerException because from main() you are trying to access the loginApplication() method right in the begining, which requires an active instance of the WebDriver i.e. the driver to findElement(By.name("username")); & findElement(By.name("password")); and perform sendKeys() method on the HTML DOM.
The solution would be to first access the launchApplication() method so you have an active instance of driver and IE Browser. Next you can access loginApplication() method.
Here is your working code block:
package demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Q45474353_NPE
{
public WebDriver driver;
public void launchApplication()
{
System.setProperty("webdriver.ie.driver", "C:\\Utility\\BrowserDrivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://www.gcrit.com/build3/admin/");
}
public void loginApplication(String Username, String Password)
{
driver.findElement(By.name("username")).sendKeys(Username);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.id("tbd1")).click();
}
public void closeBrowser()
{
driver.close();
}
public static void main(String[] args)
{
Q45474353_NPE obj = new Q45474353_NPE();
obj.launchApplication();
obj.loginApplication("admin", "admin#123");
obj.closeBrowser();
}
}

Need to take full webpage screen shot of www.flipkart.com using webdriver

I need to capture the entire webpage of www.flipkart.com using web driver.
I have written the below code for the same. But its not working. Please suggest.
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class ScreenShot {
public static WebDriver driver = null;
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("webdriver.gecko.driver","C:\\Eclipse\\Drivers\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.flipkart.com/");
Thread.sleep(10000);
//Take the screenshot of the entire home page and save it to a png file
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
//Screenshot screenshot = new AShot().takeScreenshot(driver, driver.findElement(By.xpath(".//*[#id='container']")));
ImageIO.write(screenshot.getImage(), "PNG", new File("C:\\Users\\Vishvambruth JT\\Desktop\\home.png"));
driver.quit();
}
}
try once with below code.
public class Flipcart {
public WebDriver d;
Logger log;
#Test
public void m1() throws Exception
{
try
{
d=new FirefoxDriver();
d.manage().window().maximize();
d.get("https://www.flipkart.com/");
String pagetitle=d.getTitle();
}
catch(Exception e)
{
System.out.println("something happened, look into screenshot..");
screenShot();
}
}
public void screenShot() throws Exception
{
Files.deleteIfExists(Paths.get("G:\\"+"Test results.png"));
System.out.println("previous pics deleted...");
File scrFile = ((TakesScreenshot)d).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile,new File("G:\\"+"Test results.png"));
}
}

Null pointer exception in Java while calling the library

Now i modified the code but still i am getting Null Pointer Exception
Below is my modified code
enter code here
package lib;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeMethod;
//#SuppressWarnings("unused")
public class Login {
WebDriver driver;
#BeforeMethod
void Initalisation()
{
System.setProperty("webdriver.ie.driver", "C:\\Eclipse\\IEDriverServer.exe");
DesiredCapabilities capability=new DesiredCapabilities();
capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
InternetExplorerDriver driver=new InternetExplorerDriver(capability);
driver.get("http://segotn11540.rds.volvo.com/vss_connect_testr1/Login/Login.aspx");
}
public Login(String UserName,String BrandName)
{
driver.findElement(By.xpath("//input[#name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[#name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[#name='CmdLogin']")).click();
String Title=driver.getTitle();
if(!Title.contains("VSS 4.0"))
{
System.out.println(UserName+""+"does not exists");
driver.quit();
}
CheckForCancel();
}
private void CheckForCancel() {
if(!driver.findElements(By.id("Cancel")).isEmpty())
{
driver.findElement(By.id("Cancel")).click();
}
}
}
Now I will create the main Java file
Blockquote
This will initalise the login with the parameters supplied
Import Login library
public class MessageBoard {
public static void main(String[] args)
{
Login login=new Login("TYP40FI","Volvo");
}
}
What is wrong in above code
Try to initialize the driver variable as
WebDriver driver = new WebDriver();
public Login(String UserName,String BrandName)
{
//Add this line in your code as you are trying in IE
driver = new InternetExplorerDriver();
driver.findElement(By.xpath("//input[#name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[#name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[#name='CmdLogin']")).click();
String Title=driver.getTitle();
if(!Title.contains("VSS 4.0"))
{
System.out.println(UserName+""+"does not exists");
driver.quit();
}
CheckForCancel();
}
Debug and check: Is Initalisation() being called in the beginning?
Usually #BeforeMethod is called before test starts, so where is your #Test function. (syntax could be wrong)
If you don't really care about #Test property, that means your Main function needs to call Initalisation() before calling Login(...), otherwise the driver is not set yet (aka Null)

Wrong test executed first in Selenium TestNG

In the below script I want to run the Test 'Login' first and then the 'CreateCompany'. But whenever I try to run the script always the control goes to the 'CreateCompany' test at first. And since the user is not already logged in the script execution fails. Please someone tell me what is wrong with the script below.
package MyPackage;
import java.util.concurrent.TimeUnit;
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.DataProvider;
import org.testng.annotations.Test;
import MyPackage.PageObjects.CompanyListing;
import MyPackage.PageObjects.LoginPage;
public class SetUpCompany {
public static WebDriver driver;
public String BaseURL=LoginPage.BaseURL();
#BeforeClass
public static void setup() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
//public static WebDriver driver = new FirefoxDriver();
#Test(dataProvider="UserData")
void Login(String username, String password, String usertype){
//dr.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
if(usertype.equals("SuperAdmin")){
String LoginURL=BaseURL+"/Manage";
driver.get(LoginURL);
LoginPage.UsernameBox(driver).sendKeys(username);
LoginPage.PasswordBox(driver).sendKeys(password);
LoginPage.LoginButton(driver).click();
//System.out.println("Hello Super admin!");
}
}
#Test(dataProvider="CompanyData")
void CreateCompany(String FrstNm, String LastNm, String CmpnyNm, String Email, String Phone, String Cell, String Web){
System.out.println("I'm here");
String ManageCompanyURL=BaseURL+"/Manage/Company";
driver.get(ManageCompanyURL);
CompanyListing.AddCmpnyBtn(driver).click();
}
#DataProvider(name="UserData")
public Object[][] loginData() {
Object[][] LoginArray = DataReader.getExcelData("E:/DataBase.xls","LoginData");
return LoginArray;
}
#DataProvider(name="CompanyData")
public Object[][] CompanyInfo() {
Object[][] CompanyArray = DataReader.getExcelData("E:/DataBase.xls","CompanyInfo");
return CompanyArray;
}
#AfterClass
public static void teardown() {
driver.close();
driver.quit();
}
}
What you have is dependent tests where CreateCompany is dependent upon login test.
You should be using dependsOnMethods. Read more here
Try writing priorities in your #Test annotations in TestNG to set the execution sequence. Here's how to do it -
#Test(priority=1, dataProvider="UserData")
void Login(String username, String password, String usertype){
//Your login code
}
#Test(priority=2, dataProvider="CompanyData")
void CreateCompany(String FrstNm, String LastNm, String CmpnyNm, String Email, String Phone, String Cell, String Web){
//Your CreateCompany code
}
More info on priorities in TestNG. Hope this helps.