I'm new to Selenium Webdriver, I have a few question :
First, I have 2 class, 'Login.java' and 'SelectCity.java
Class 1 : Login.java
invalidLogin
validLogin
Class 2 : SelectCity.java
For now, in Login.java I wrote
#After
public void tearDown() throws Exception {
driver.close();
}
which mean the browser will closed after finish run right?
Here is my question :
How to make after I run validLogin, it will continue to run the next class (SelectCity.java)?
Is it possible to do that?
How to make last browser (which test valid login) didn't get close?
My current Login.java class :
public class Login extends SelectCityAfterLogin{
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://mysite/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLoginInvalidPass() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("user1");
driver.findElement(By.id("txtPassword")).sendKeys("somePassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Invalid User or Password", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginInvalidUsername() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("username");
driver.findElement(By.id("txtPassword")).sendKeys("somepassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Invalid User or Password", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginNoUsername() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("");
driver.findElement(By.id("txtPassword")).sendKeys("somePassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Please fill username and password.", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginNoPassword() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("username");
driver.findElement(By.id("txtPassword")).sendKeys("");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Please fill username and password.", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginValid() throws Exception{
//SelectRoleAfterLogin selectRole = SelectRoleAfterLogin();
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("myUsername");
driver.findElement(By.id("txtPassword")).sendKeys("password");
driver.findElement(By.id("lbLogin")).click();
Thread.sleep(3000);
}
}
Thx
Yes you can run selectcity after login
You should Extend your First class to Second class
In your Login.java extend it to selectcity java like below
Public class login extends Selectcity {
After your validlogin
create a new instance for selectcity (If you are using #test, create the below in that)
selectcity test = new selectcity()
Once after your valid login do the following
test.(will fetch you the methods available in selectcity.java)
By this way you can call once class to another.
Let me know if this helps
UPDATE :
if selectcityAfterlogin in public class Login extends **SelectCityAfterLogin** is your second class name, then you are creating an incorrect object i guess
In your public login class please check whether your are extending the proper second class name
In #test method
#Test
public void testLoginValid() throws Exception{
//SelectRoleAfterLogin selectRole = SelectRoleAfterLogin();
it should be
SelectCityAfterLogin selectrole = new SelectCityAfterLogin()
selectrole.(will fetch you the methods of second city)
Please let me know if this helps.
One better solution would be to create multiple methods than multiple #test. You can call these to single #test suite.
I am assuming, you have 2 classes 'Login.java' and 'SelectCity.java'
as follows:
Class 1 : Login.java
public void invalidLogin (WebDriver driver){
//some operations
}
public void validLogin (WebDriver driver){
//some operations
}
Class 2 : SelectCity.java
public void selectCity (Webdriver Driver){
//some operations
}
Class 3: LoginAndSelectCity.java
public static void main(String args []){
WebDriver driver = new FirefoxDriver();
Login.validLogin(driver);
SelectCity.selectCity(driver);
}
If all classes should be in same package then only it works else you need to import packages or create new child to do inheritance of the classes.
Related
#Aftertest
#AfterSuite
#AfterClass Nothing is helpful in my case when we talk about sending the latest reports in the email.
#AfterSuite
public void statusupdate() throws Exception
{
SendMail.execute();
}
This is what I am doing and every time I am getting an older version of my emailable-report.html as I am struggling with JAVA as well so hopefully someone can help me understanding what is wrong here. My assumption is I am sending the email before the fresh report is generated but have no clue what to do next. Thanks for the patience and your replies.
Best you can do is to help yourself with Listeners for reports, instead of an #afterXxxx method.
So you can do something like:
import org.testng.annotations.Listeners;
#Listeners(TestListener.class)
public class MyTestClass {
#Test
public void myTest {
doTest();
}
}
Where your Listener has your SendMail action in the onFinish method:
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestListener implements ITestListener {
#Override
public void onTestStart(ITestResult result) {
}
#Override
public void onTestSuccess(ITestResult result) {
}
#Override
public void onTestFailure(ITestResult result) {
}
#Override
public void onTestSkipped(ITestResult result) {
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
#Override
public void onStart(ITestContext context) {
}
#Override
public void onFinish(ITestContext context) {
SendMail.execute();
}
}
I hope this does what you need, if not let me know.
Finally I am able to get the latest .html report by implementing extent reports and TestNG listeners in my framework. I am using 7.0 TestNG and its limitation is that it does not update the emailable-report.html so to overcome this problem you will have to implement extent reports where you will always get the latest .html fancy report which you can send through email in onFinish method of your listener class. But before jumping in you have to understand listeners and extent reports rest is given below. Also thanks #rodrigo for giving me a direction :)
public class TestClass{
WebDriver driver=null;
public ExtentHtmlReporter htmlReporter;
public ExtentReports extent;
public ExtentTest test;
public static String getScreenshot(WebDriver driver, String screenshotName) throws IOException {
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date(0));
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
// after execution, you could see a folder "FailedTestsScreenshots" under src folder
String destination = System.getProperty("user.dir") + "/Screenshots/" + screenshotName + dateName + ".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
return destination;
}
#BeforeTest()
#Parameters("browser")
public void setup(String browsername) {
if(browsername.equalsIgnoreCase("chrome"))
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
}
else if(browsername.equalsIgnoreCase("firefox"))
{
WebDriverManager.firefoxdriver().setup();
driver=new FirefoxDriver();
}
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"\\test-output\\myReport.html");
htmlReporter.config().setDocumentTitle("Automation Report"); // Tile of report
htmlReporter.config().setReportName("Functional Testing"); // Name of the report
htmlReporter.config().setTheme(Theme.DARK);
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// Passing General information
extent.setSystemInfo("Host name", "NerdBox");
extent.setSystemInfo("Environemnt", "QA");
extent.setSystemInfo("user", "AB");
}
#Test(priority=1,enabled=true)
public void SubmitQuestions() throws Exception {
driver.manage().window().maximize();
driver.get("https://com/questions");
driver.findElement(By.xpath("/html/body/div/div/div[3]/div/div/div[1]/div/div/div[2]/div")).click();
}
#AfterMethod(alwaysRun=true)
public void end(ITestResult result) throws IOException
{
test= extent.createTest("The Test is "+result.getName());
if (result.getStatus() == ITestResult.FAILURE) {
test.log(Status.FAIL, "TEST CASE FAILED IS " + result.getName()); // to add name in extent report
test.log(Status.FAIL, "TEST CASE FAILED IS " + result.getThrowable()); // to add error/exception in extent report
String screenshotPath = NerdboxJobSubmit.getScreenshot(driver, result.getName());
test.addScreenCaptureFromPath(screenshotPath);// adding screen shot
} else if (result.getStatus() == ITestResult.SKIP) {
test.log(Status.SKIP, "Test Case SKIPPED IS " + result.getName());
}
else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(Status.PASS, "Test Case PASSED IS " + result.getName());
}
}
#AfterTest(alwaysRun=true)
public void flush() throws Exception
{
System.out.println("After test");
extent.flush();
driver.quit();
}
This is My setup class:
public class SetupClass {
//AppiumDriver<MobileElement> driver;
AndroidDriver<MobileElement> d;
public Properties prop =null;
public File file;
public FileInputStream fis;
#Parameters(value ="Android")
#BeforeSuite
public void setup(String Android) throws IOException, Exception{
LoadPropertiesFile();
DesiredCapabilities caps = new DesiredCapabilities();
/*caps.setCapability("plateformName", "Android");
caps.setCapability(CapabilityType.PLATFORM_NAME, "Android");*/
if (Android.equalsIgnoreCase("Moto_g4_Plus")) {
caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.0");
caps.setCapability(MobileCapabilityType.UDID, "ZY223WZSQ9");
caps.setCapability(MobileCapabilityType.DEVICE_NAME, "Moto G4 Plus");
}
caps.setCapability("app", "C:\\Users\\amarjeet.sharma\\eclipse-workspace\\com.asm.app\\src\\test\\resources\\app\\asmVisit.apk");
caps.setCapability("appPackage", "com.sumasoft.net.asmscheduler");
caps.setCapability("appActivity", "md5f32326382a711c73d2de951d70f3bd5e.MainActivity");
caps.setCapability("autoGrantPermissions", true);
URL url;
try {
url = new URL("http://127.0.0.1:4723/wd/hub");
//driver = new AppiumDriver<MobileElement>(url, caps);
d = new AndroidDriver<MobileElement>(url, caps);
Thread.sleep(5000);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("Cause is:" +e.getCause());
System.out.println("Message is:" +e.getMessage());
e.printStackTrace();
}
}
public void LoadPropertiesFile() throws IOException {
prop=new Properties();
file =new File(System.getProperty("user.dir")+"/src/main/resources/config.properties");
fis=new FileInputStream(file);
prop.load(fis);
//System.out.println(prop.getProperty("userId"));
}
//#AfterTest
public void TearDown() throws IOException{
System.out.println("Quit");
d.quit();
}
}
This is My LoginTest
public class LoginTest extends SetupClass{
#Test(priority = 1)
public void login() throws Exception {
LoginPage lp = new LoginPage(d);
//System.out.println(prop.getProperty("userId"));
lp.userName(prop.getProperty("userId"));
Thread.sleep(500);
lp.password(prop.getProperty("Passwd"));
Thread.sleep(500);
lp.loginButton();
}
}
And this is my create new journey class
public class AddJourneyTest extends SetupClass{
#Test(priority=2)
public void AddNewJourney() throws Exception {
AddjourneyPage addobj = new AddjourneyPage(d);
addobj.ClicktoAdd();
addobj.SelectFromToDate();
addobj.SelectState();
addobj.SelectCity();
addobj.ClickonSubmit();
}
}
I am getting NullPointerException for AddJourney class
I think when I run it as TestNG then the driver gets initiated for the LoginTest and holds the control. So that AddJourney class does not get driver initiated and hence getting NullPointerException.
I am using Appium Server, Java + Selenium + TestNG for the Android Application automation on Windows system with physical android device.
Maybe I am wrong. But I am not getting solution over it. Please help.
I am having an issue where if I run a test that has 6 steps, 3 pass, 1 fail, 2 skipped. It will always report as Passed in my extent reports. I am using Klov. Is it possible that I have not correctly configured the report? and if so does anyone have suggestions to fix this issue.
public class MyRunner {
#BeforeClass
public static void initialize(){
d = new Date();
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setKlovServerUrl("http://localhost");
extentProperties.setKlovProjectName("Test Project");
extentProperties.setKlovReportName("Test Report: " + d);
extentProperties.setMongodbHost("localhost");
extentProperties.setMongodbPort(27017);
extentProperties.setMongodbDatabase("klov");
}
}
#AfterClass
public static void teardown(ITestResult result){
extent.flush();
}
}
And here is my test, it is just a simple test that opens googles login page, just to make sure the extent reports will do everything I need it to
public class Google {
WebDriver driver;
#Given("^that I am on the webpage Google$")
public void thatIAmOnTheWebpageGoogle() throws Throwable {
System.setProperty("webdriver.chrome.driver","\\\\hiscox.nonprod\\profiles\\Citrix\\XDRedirect\\CaseyG\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://accounts.google.com/signin/v2/identifier?hl=en&passive=true&continue=https%3A%2F%2Fwww.google.com%2F&flowName=GlifWebSignIn&flowEntry=ServiceLogin");
driver.manage().window().maximize();
MyRunner.logger.log(Status.INFO, "Opened Google login page")
//throw new PendingException();
//extent.createTest("Step 1").pass("log");
}
#When("^I try to login$")
public void i_try_to_login() throws Throwable {
// find the username field and enters the username, then clicks next
WebElement username = driver.findElement(By.xpath("//input[#id='identifierId']"));
username.sendKeys("********");
driver.findElement(By.id("identifierNext")).click();
//finds the password field and enters the password
WebElement password = driver.findElement(By.xpath("//input[#name='password']"));
password.sendKeys("**********");
Assert.assertFalse(true);
driver.findElement(By.id("passwordNext")).click();
//throw new PendingException();
//extent.createTest("Step 2").pass("log");
}
#Then("^I will be successfully logged into Google$")
public void i_will_be_successfully_logged_into_Google() throws Throwable {
String account = "Google Account: greg casey \n" + "(klovtest#gmail.com)";
//WebElement loggedInUser = driver.findElement(By.xpath("//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]"))
//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]/a
//extent.createTest("Step 3").pass("log");
throw new PendingException();
}
}
You should use ITestListener Interface on your Listener class where extent report's test is created
OnTestStart and do other things alos as descriobed below (I have used Thread for parallel device testing so you can ignore, rest is useful)
public class Listeners extends Utilities implements ITestListener {
ExtentReports extent = ExtentReporterTool.getReport();enter code here
ExtentTest test;
ThreadLocal<ExtentTest> testObjects = new ThreadLocal<ExtentTest>();
#Override
public void onTestStart(ITestResult result) {
test = extent.createTest(result.getMethod().getMethodName());
testObjects.set(test);
}
#Override
public void onTestSuccess(ITestResult result) {
testObjects.get().log(Status.PASS, "Test Case passed");
}
#Override
public void onTestFailure(ITestResult result) {
testObjects.get().fail(result.getThrowable());
WebDriver driver;
try {
driver = (WebDriver) result.getTestClass().getRealClass().getSuperclass().getField("driver")
.get(result.getInstance()); testObjects.get().addScreenCaptureFromPath(takeScreenshot(result.getMethod().getMethodName(), driver),
result.getMethod().getMethodName());
} catch (IOException | IllegalArgumentException | SecurityException | IllegalAccessException
| NoSuchFieldException e) {
e.printStackTrace();
}
}
#Override
public void onTestSkipped(ITestResult result) {
testObjects.get().log(Status.SKIP, "Test Case skipped");
}
#Override
public void onFinish(ITestContext context) {
extent.flush();
}
}
I have a testcase that will invoke the driver as a non static variable. I also have added screenshot listener in my test case. When the test case fails The control is automatically sent to the screenshot listener, however since my driver is a NON-STATIC variable it could not be accessed in the screenshot listener. So I get nullpointer exception.
To solve this I created a simple base test class with help of stackoverflow like below and extend it in each testclass
public asbtract baseTest() {
private WebDriver driver;
public WebDriver getDriver() {
return driver;
}
#BeforeMethod
public void createDriver() {
Webdriver driver=XXXXDriver();
}
#AfterMethod
public void tearDownDriver() {
if (driver != null)
{
try
{
driver.quit();
}
catch (WebDriverException e) {
System.out.println("***** CAUGHT EXCEPTION IN DRIVER TEARDOWN *****");
System.out.println(e);
}
}
}
In my listener, I access the base class as follows
public class ScreenshotListener extends TestListenerAdapter {
#Override
public void onTestFailure(ITestResult result)
{
Object currentClass = result.getInstance();
WebDriver webDriver = ((baseTest) currentClass).getDriver();
if (webDriver != null)
{
File f = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
//etc.
}
}
My test class looks like this
#Listeners(value = FailureReport.class)
public class LoginTest extends baseTest{
Login login = new Login(getDriver());
#Test(description = "Verify Expand the Menu", priority = 0)
public void navigateloginpage() {
login.expandMenuScreenLogin();
login.navigateLoginPage();
}
#Test(description = "User login Sucessfully", priority = 1)
public void successLogin() {
login.login();
}
When I run this it gives me the error
org.testng.TestNGException:
Cannot find class in classpath: com.fbf.automation.tests.LoginTest
at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
at org.testng.xml.XmlClass.init(XmlClass.java:73)
at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:548)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:745)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1359)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:841)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:770)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:327)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
at org.testng.xml.XMLParser.parse(XMLParser.java:38)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:16)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:9)
at org.testng.xml.Parser.parse(Parser.java:172)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:302)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:45)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Process finished with exit code 0
Later when I changed my test class as follows it ran correctly
#Listeners(value = FailureReport.class)
public class LoginTest extends baseTest{
Login login;
#Test(description = "Verify Expand the Menu", priority = 0)
public void navigateloginpage() {
login = new Login(getDriver());
login.expandMenuScreenLogin();
login.navigateLoginPage();
}
#Test(description = "User login Sucessfully", priority = 1)
public void successLogin() {
login.login();
}
Isn't it possible to declare the code
login = new Login(getDriver());
outside #test method rather than writing it inside the #test method. Or are there anyother alternative ways I can call the above code
You may create Login object inside #BeforeClass method
#BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
login = new Login(getDriver());
}
I have used Page Object Model design pattern along with Cucumber. So for this I have created two pages named as abstractPage and loginPage but on running the script i get null pointer exception even when i have already initialize the webelements using pagefactory , please have a look at below code:
abstractPage:
public class abstractPage {
protected WebDriver driver;
public static loginPage lpOBJ;
public void openBrowsernURLhit() {
driver=new FirefoxDriver();
driver.get("http://www.facebook.com");
PageFactory.initElements(driver, loginPage.class);
}
}
loginPage:
public class loginPage extends abstractPage {
#FindBy(name = "email")
public WebElement username;
#FindBy(name = "pass")
public WebElement password;
#FindBy(id = "u_0_2")
public WebElement loginButon;
public void loginIntoApp() {
String url=driver.getCurrentUrl();
System.out.println("the url is::::::::::::::::"+url);
username.sendKeys("testuser");
password.sendKeys("123");
}
public void clicklogn() {
loginButon.click();
}
}
And then I have a class stepDefination from where I am calling the above methods of login class. Browser is opened fine and url is hit but when it goes inside loginintoapp() method it throws exception on first line itself.
public class SmokeTest {
#Given("^Open Firefox and start application$")
public void Open_Firefox_and_start_application() throws Throwable {
abstractPage obj = new abstractPage();
obj.openBrowsernURLhit();
}
#When("^I enter valid \"([^\"]*)\" and \"([^\"]*)\"$")
public void I_enter_valid_username_and_password(String arg1, String arg2) throws Throwable {
loginPage lpobj = new loginPage();
lpobj.loginIntoApp();
}
#Then("^user should be able to login successfully$")
public void user_should_be_able_to_login_successfully() throws Throwable {
loginPage lpobj = new loginPage();
lpobj.clicklogn();
}
}
I also have a TestRunner class where i have glued my stepDefination:
#RunWith(Cucumber.class)
#CucumberOptions(
features= "features",
glue= {"stepDefination"},
plugin= {"html:target/cucumber-html-report"}
)
public class TestRunner {
}
But on running the above script I always get NullPointerException in first line ofloginIntoApp() method.I have already used Pagefactory to initialize webelements but i guess "driver" variable is not getting initialized in Login class though i have inherited asbtract class where i m instantiating the driver due to which it is throwing null pointer.Please see what I am i doing wrong here.Error is as follows:
1 Scenarios ([31m1 failed[0m)
3 Steps ([31m1 failed[0m, [36m1 skipped[0m, [32m1 passed[0m)
0m18.149s
java.lang.NullPointerException
at pages.loginPage.loginIntoApp(loginPage.java:22)
at stepDefination.SmokeTest.I_enter_valid_username_and_password(SmokeTest.java:33)
at ?.When I enter valid "t1#gmail.com" and "pass"(MyApp.feature:5)
Thanks
please add the following constructor. It may solve the issue.
public loginPage(){
PageFactory.initElements(driver, loginPage.class);
}
you can put outside as well like,
public void loginIntoApp() {
String url=abstractPage.driver.getCurrentUrl();
System.out.println("the url is::::::::::::::::"+url);
loginPage lp=PageFactory.initElements(abstractPage.driver, loginPage.class);
lp.username.sendKeys("testuser");
lp.password.sendKeys("123");
}
other way is,
public class SmokeTest extends abstractPage {
#Given("^Open Firefox and start application$")
public void Open_Firefox_and_start_application() throws Throwable {
openBrowsernURLhit();
}
#When("^I enter valid \"([^\"]*)\" and \"([^\"]*)\"$")
public void I_enter_valid_username_and_password(String arg1, String arg2) throws Throwable {
loginPage lpobj = PageFactory.initElements(driver, loginPage.class);
lpobj.loginIntoApp();
}
#Then("^user should be able to login successfully$")
public void user_should_be_able_to_login_successfully() throws Throwable {
loginPage lpobj = PageFactory.initElements(driver, loginPage.class);
lpobj.clicklogn();
}
}
the simplest way to solve the problem is to make your driver object static.
protected static WebDriver driver;
as you are using page factory, you also need to initiazlize the page object, otherwise all the the WebElement will be null
public loginPage(){
PageFactory.initElements(driver, this);
}
or this, which I don't think is a good practice and people should avoid this.
public void loginIntoApp() {
String url=driver.getCurrentUrl();
System.out.println("the url is::::::::::::::::"+url);
PageFactory.initElements(driver, this);
username.sendKeys("testuser");
password.sendKeys("123");
}