Mvn Test cmd line Build Failure, Test Works in Eclipse - java

This is the circumstance. I am an QA Automation Engineer and right now I am being charged with setting up our CI framework in Jenkins but right now I am having issues with Maven. I am getting this error below when I try to run the mvn test command. However the tests work flawlessly in eclipse when run as maven test.
T E S T S
-------------------------------------------------------
Running TestSuite
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configur
ator#3830f1c0
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configur
ator#bd8db5a
Tests run: 16, Failures: 1, Errors: 0, Skipped: 14, Time elapsed: 0.66 sec <<< F
AILURE!
beforeTest(fcstestingsuite.fsnrgn.LoginTest) Time elapsed: 0.442 sec <<< FAILU
RE!
java.lang.IllegalStateException: The path to the driver executable must be set b
y the webdriver.chrome.driver system property; for more information, see https:/
/github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be dow
nloaded from http://chromedriver.storage.googleapis.com/index.html
at com.google.common.base.Preconditions.checkState(Preconditions.java:19
9)
at org.openqa.selenium.remote.service.DriverService.findExecutable(Drive
rService.java:109)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDrive
rService.java:32)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExe
cutable(ChromeDriverService.java:137)
at org.openqa.selenium.remote.service.DriverService$Builder.build(Driver
Service.java:296)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(C
hromeDriverService.java:88)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:116)
at fcstestingsuite.fsnrgn.LoginTest.beforeTest(LoginTest.java:54)
Results :
Failed tests: beforeTest(fcstestingsuite.fsnrgn.LoginTest): The path to the dr
iver executable must be set by the webdriver.chrome.driver system property; for
more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver.
The latest version can be downloaded from http://chromedriver.storage.googleapis
.com/index.html
Tests run: 16, Failures: 1, Errors: 0, Skipped: 14
As you can see it is related to my chrome system property/path. In my project I have a test package and page object package. I set my chrome system property in the object class and import that class into the test class which works fine in eclipse. I'm not quite sure why Maven is having an issue with this. See sample object and test class below
Page Class
package pageobjectfactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
// URL = http://www.ourfsn.com/myfsn/
public class Ourfsnlogin {
#FindBy(id="ctl00_ContentPlaceHolder1_tbxUname")
WebElement login;
#FindBy(id="ctl00_ContentPlaceHolder1_tbxPword")
WebElement password;
#FindBy(id="ctl00_ContentPlaceHolder1_btnSubmit")
WebElement submit;
#FindBy(name="ctl00$ContentPlaceHolder1$rptAccounts$ctl01$AccountSwitch")
WebElement PETSMARTUS;
#FindBy(name="ctl00$ContentPlaceHolder1$rptAccounts$ctl02$AccountSwitch")
WebElement PETSMARTCAD;
#FindBy(name="ctl00$ContentPlaceHolder1$rptAccounts$ctl03$AccountSwitch")
WebElement PETSMARTPR;
#FindBy(id="ctl00_lblTopLogin")
WebElement PETSMARTUSASSERT;
#FindBy(id="ctl00_lblTopLogin")
WebElement PETSMARTCAASSERT;
#FindBy(id="ctl00_lblTopLogin")
WebElement PETSMARTPRASSERT;
#FindBy(id="ctl00_Menu1_16")
WebElement LogoutButton;
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\dmohamed\\Documents\\Testing Environment\\Testing Environment\\Web Drivers\\chromedriver_win32 (1)\\chromedriver.exe");
WebDriver chromedriver = null; new ChromeDriver();
driver= chromedriver;
}
//Send user name in textbox
public void sendUserName(String strUsername){
login.sendKeys("ebluth");}
public void sendUserNameServiceCenter(String strUsername){
login.sendKeys("servicecenter");}
public void sendUserNameSP(String strUsername){
login.sendKeys("4328701");
}
//Send Password
public void sendPassword(String strPassword){
password.sendKeys("password");}
//submitting credentials
public void clicksubmit(){
submit.click();}
//Checking US PAge
public void USAssertion(){
PETSMARTUS.isEnabled();
}
//Checking CAD page
public void CAAssertion(){
PETSMARTCAD.isEnabled();}
//Checking PR Page
public void PRAssertion(){
PETSMARTPR.isEnabled();}
//click us link
//Checking US PAge
public void USclick(){
PETSMARTUS.click();
}
//Checking CAD page
public void CAclick(){
PETSMARTCAD.click();}
//Checking PR Page
public void PRclick(){
PETSMARTPR.click();}
//Click on
public void USPageValidation(){
Assert.assertTrue(PETSMARTUSASSERT.getText().contains("PETM-US"), "Incorrect Page [US,CA,PR]");
}
public void PRPageValidation(){
Assert.assertTrue(PETSMARTPRASSERT.getText().contains("PETM-PR"),"Incorrect Page [US,CA,PR]");
}
public void CAPageValidation(){
Assert.assertTrue(PETSMARTCAASSERT.getText().contains("PETM-CN"),"Incorrect Page [US,CA,PR]");
}
//Log out
public void Logout (){
LogoutButton.click();
}}
Test Class
package fcstestingsuite.fsnrgn;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import pageobjectfactory.Ourfsnlogin;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;
public class LoginTest {
static WebDriver driver;
Ourfsnlogin LoginPage;
#Test (priority=1)
public void USPageTest() {
LoginPage.sendUserName("ebluth");
LoginPage.sendPassword("password");
LoginPage.clicksubmit();
LoginPage.USclick();
LoginPage.USPageValidation();
}
#Test(priority=2)
public void CAPageTest(){
LoginPage.sendUserName("ebluth");
LoginPage.sendPassword("password");
LoginPage.clicksubmit();
LoginPage.CAclick();
LoginPage.CAPageValidation();
}
#Test (priority=3)
public void PRPageTest(){
LoginPage.sendUserName("ebluth");
LoginPage.sendPassword("password");
LoginPage.clicksubmit();
LoginPage.PRclick();
LoginPage.PRPageValidation();
}
#AfterMethod
public void aftermethod(){
LoginPage.Logout();
}
#BeforeTest
public void beforeTest() {
Ourfsnlogin.driver=new ChromeDriver();
//setting global explicit wait
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
Ourfsnlogin.driver.get("http://www.ourfsn.com/myfsn");
//initiating elements in page factory
LoginPage= PageFactory.initElements(Ourfsnlogin.driver, Ourfsnlogin.class);
}
#AfterTest
public void afterTest() {
Ourfsnlogin.driver.quit();
}
}

The structure of your tests seems incorrect. You have a main method in the LoginPage - which is doing driver instantiation. Where is the main method being called from? Your beforetest also has a driver instantiation code which is called by testng but there you are not setting the chromedriver property.
Ideally the driver instantiation code should be written at one place and be consumed from the rest of the testcases.

Related

"No tests found. Nothing was run" error in selenium automation using TestNG

Given below is the code that I coded using selenium in eclipse.
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
class GoogleSearchTest {
#Test
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver","C:\\Users\\acer\\Downloads\\selenium\\geckodriver.exe");
WebDriver driver =new FirefoxDriver();
driver.get("https://www.google.com/");
WebElement we1 = driver.findElement(By.name("q"));
we1.sendKeys("GMAIL");
we1.sendKeys(Keys.ENTER);
WebDriverWait wait1 = new WebDriverWait(driver, 5);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h3[text()='E-mail - Sign in - Google Accounts']"))).click();
Thread.sleep(10000);
driver.findElement(By.id("identifierId")).sendKeys("2017cs102#stu.ucsc.cmb.ac.lk");
driver.findElement(By.xpath("//*[#id='identifierNext']/div/span/span")).click();
Thread.sleep(10000);
driver.findElement(By.name("password")).sendKeys("mmalsha425#gmail.com");
driver.findElement(By.xpath("//*[#id='passwordNext']/div/span/span")).click();
}
}
It gives the following error.
[TestNG] No tests found. Nothing was run
Usage: <main class> [options] The XML suite files to run
I have already installed TestNG plugin.What can I do to fix this problem??
Change the main function name. You should not use it while using TestNG
#Test
public void test() throws InterruptedException {
System.setProperty("webdriver.gecko.driver","C:\\Users\\acer\\Downloads\\selenium\\geckodriver.exe");
WebDriver driver =new FirefoxDriver();
You don't need to write main() method, TestNg do that by itself.
class GoogleSearchTest {
#Test
public void test() throws InterruptedException{
//your code here
.....
}
}
If you want to call from main(), simply:
import org.testng.TestNG;
public class Master {
public static void main(String[] args) {
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { GoogleSearchTest.class });
testng.run();
}
}
But note, in GoogleSearchTest class don't put public static void main for #Test
This error message...
[TestNG] No tests found. Nothing was run
Usage: <main class> [options] The XML suite files to run
...implies that the TestNG found no tests hence nothing was executed.
TestNG
TestNG is an annotation-based test framework which needs a marker annotation type to indicate that a method is a test method, and should be run by the testing tool. Hence, while using testng as you use annotations and you don't have to call the main() method explicitly.
Solution
The simple solution would be to replace the main() method with a test method name e.g. test() and keep the #Test annotation as follows:
// your imports
class GoogleSearchTest {
#Test
public void test() throws InterruptedException {
System.setProperty("webdriver.gecko.driver","C:\\Users\\acer\\Downloads\\selenium\\geckodriver.exe");
// other lines of code
}
}

When i want to run this program instead of run as application it will shown like "run as configuration". Why it will ask like this

I am very new to the selenium section please check this code in that when I want to run this application at its not run. Instead of running it will it will ask like run as configuration.
package com.shiftwizard.application;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Login {
public WebDriver driver;
public void positive()
{
System.setProperty("webdriver.chrome.driver", "D:\\prasanth softwares\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://devtest-new.myshiftwizard.com");
driver.findElement(By.name("txtUserName")).sendKeys("cs#shiftwizard.com");
driver.findElement(By.name("txtPassword")).sendKeys("P#ssword!1");
driver.findElement(By.name("btnLogin1")).click();
}
public void negitive()
{
System.setProperty("webdriver.chrome.driver", "D:\\prasanth softwares\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.findElement(By.name("txtUserName")).sendKeys("cs#shiftwizard.com");
driver.findElement(By.name("txtPassword")).sendKeys("P#ssword1");
driver.findElement(By.name("btnLogin1")).click();
System.out.println(driver.findElement(By.id("reqPass")));
}
public void close()
{
driver.close();
}
}
This is my code while i want to run this application i get like run as configuration listed of the run as java application.
Try this:
// set you package name here
package Prabha;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Login {
public static WebDriver driver;
WebDriverWait wait5s = new WebDriverWait(driver,5);
#BeforeClass
public static void setUpClass() {
// set your exe location here
System.setProperty("webdriver.chrome.driver", "C:\\Users\\pburgr\\Desktop\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
// set your profile folder here or remove this line
options.addArguments("user-data-dir=C:\\Users\\pburgr\\AppData\\Local\\Google\\Chrome\\User Data");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
}
#Before
public void setUp() {}
#After
public void tearDown() {}
#AfterClass
public static void tearDownClass() {driver.close();driver.quit();}
#Test
public void login() throws InterruptedException {
// calling method "positive", the method "negative" still unused in this class
positive();
}
public void positive() throws InterruptedException {
driver.get("https://devtest-new.myshiftwizard.com");
// wait 5 seconds to load the page
wait5s.until(ExpectedConditions.elementToBeClickable(By.name("txtUserName"))).sendKeys("cs#shiftwizard.com");
driver.findElement(By.name("txtPassword")).sendKeys("P#ssword!1");
driver.findElement(By.name("btnLogin1")).click();
Thread.sleep(5000);
// to be continued...
}
public void negative() throws InterruptedException {
driver.get("https://devtest-new.myshiftwizard.com");
// wait 5 seconds to load the page
wait5s.until(ExpectedConditions.elementToBeClickable(By.name("txtUserName"))).sendKeys("cs#shiftwizard.com");
driver.findElement(By.name("txtPassword")).sendKeys("intentionally_wrong_password");
driver.findElement(By.name("btnLogin1")).click();
Thread.sleep(5000);
// to be continued...
}
}
The username seems to be invalid, but I believe you'll manage.

Fluentlenium and cucumber tests not starting

I have a cucumber and fluentlenium project that doesn't start when i run the CucumberRunner. It just skips all the tests .I tried to find a solution on internet but didn't figured out the problem so far. A little bit of help would be nice.
This is are my steps:
public class LoginPageSteps extends BaseTest {
public LoginPageSteps() throws Exception {
super();
}
#Page
LoginPage loginPage;
#Given("^I am on login page$")
public void goToLoginPage(){
goTo(loginPage);
}
#When("^I enter username as '(.*?)'$")
public void enterUsername(String username) {
waitAndFill(loginPage.username, username);
}
#And("^I enter password as '(.*?)'$")
public void enterPassword(String password) {
waitAndFill(loginPage.password, password);
waitUntilCliclableAndClick(loginPage.loginButton);
}
#Then("^Login should be succesfull$")
public void checkLoginStatus() {
assertTrue(getDriver().getCurrentUrl().contains("login_attempt=1"));
}
}
This is my BaseTest.class :
public class BaseTest extends FluentCucumberTest {
#Page
AccountPage accountPage;
#Before
public void before(Scenario scenario) {
super.before(scenario);
}
#After
public void after(Scenario scenario) {
super.after(scenario);
}
#Override
public WebDriver newWebDriver() {
System.setProperty("webdriver.gecko.driver", "../cucumber-test/src/test/resources/geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
return driver;
}
public void waitUntilCliclableAndClick(FluentWebElement element) {
await().atMost(5, TimeUnit.SECONDS).until(element).clickable();
element.click();
}
public void waitAndFill(FluentWebElement element, String data) {
await().atMost(5, TimeUnit.SECONDS).until(element).displayed();
element.fill().with(data);
}
}
And this is my feature file :
Feature: valid-login
Scenario:
Given I am on login page
When I enter username as "myusername"
And I enter password as "mypassword"
Then Login should be succesfull
And this is the runner :
#RunWith(Cucumber.class)
#CucumberOptions(features={"src/test/resources/features"})
public class CucumberRunner {
}
Your Cucumber runner is called CucumberRunner
This may be an issue if you build using Maven. The testrunner in Maven, Surefire, searches for classes named XXXXTest or TestXXXX. Your runner class will not be found.
Try to rename your Cucumber runner to CucumberRunnerTest and see if it solves the problem.
Found this example project which might be helpful to you.
Although I've cloned / ran this example project, the cucumber version was old and needed an update.
Here's what I've done to make the project work:
Updated fluentlenium-cucumber, fluentlenium-assertj to 3.3.0, cucumber-core, cucumber-junit, cucumber-java, cucumber-picocontainer to 1.2.5 as well as junit and htmlunit-driver to the latest versions in pom.xml.
Step file looks like this:
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import org.fluentlenium.adapter.cucumber.FluentCucumberTest;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.TimeUnit;
public class BasicStep extends FluentCucumberTest {
#Before
public void before(Scenario scenario) {
}
#Override
public WebDriver newWebDriver() {
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");
WebDriver driver = new FirefoxDriver();
return driver;
}
#Given("I open Google")
public void iOpenGoogle() {
this.initFluent(new newWebDriver());
goTo("http://google.com");
await().atMost(5, TimeUnit.SECONDS);
assertThat(window().title()).contains("Google");
}
#After
public void after(Scenario scenario){
super.after(scenario);
}
}
And the test file:
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(features = "src/test/resources/toto")
public class BasicTest {
}
New test result:
Hope you get it working!

How to make the opening of browser(all test in one browser) static in testng for selenium

I am using selenium and testNG framework for my project.
Now what is happening is each class is opening up a browser and then run its methods, eg, if I have five classes, then five browsers will open simultaneously and then run the tests.
I want to Open Browser at the start once and run all the methods and then close it.
public class openSite
{
public static WebDriver driver;
#test
public void openMain()
{
System.setProperty("webdriver.chrome.driver","E:/drive/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://vtu.ac.in/");
}
#test
//Clicking on the first link on the page
public void aboutVTU()
{
driver.findElement(By.id("menu-item-323")).click();
}
#Test
//clicking on the 2nd link in the page
public void Institutes()
{
driver.findElement(By.id("menu-item-325")).click();
}
Now What I want is the testNG should open browser once and open vtu.ac.in once and then execute the methods aboutVTU and Institutes and give me the result
You already declared the type for driver in your field declarations. Redeclaring it in openMain() is your problem. It should look like this.
import static org.testng.Assert.assertNotNull;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class OpenSite {
private WebDriver driver;
#BeforeClass(alwaysRun=true)
public void openMain()
{
System.setProperty("webdriver.chrome.driver","/usr/local/bin/chromedriver");
driver = new ChromeDriver();
driver.get("http://vtu.ac.in/");
}
#Test
//Clicking on the first link on the page
public void aboutVTU()
{
assertNotNull(driver);
driver.findElement(By.id("menu-item-323")).click();
}
#Test(dependsOnMethods="aboutVTU")
//clicking on the 2nd link in the page
public void Institutes()
{
assertNotNull(driver);
driver.findElement(By.id("menu-item-325")).click();
}
}

Maintain and re-use existing webdriver browser instance - java

Basically every time I run my java code from eclipse, webdriver launches a new ie browser and executes my tests successfully for the most part. However, I have a lot of tests to run, and it's a pain that webdriver starts up a new browser session every time. I need a way to re-use a previously opened browser; so webdriver would open ie the first time, then the second time, i run my eclipse program, I want it to simply pick up the previous browser instance and continue to run my tests on that same instance. That way, I am NOT starting up a new browser session every time I run my program.
Say you have 100 tests to run in eclipse, you hit that run button and they all run, then at about the 87th test you get an error. You then go back to eclipse, fix that error, but then you have to re-run all 100 test again from scratch.
It would be nice to fix the error on that 87th test and then resume the execution from that 87th test as opposed to re-executing all tests from scratch, i.e from test 0 all the way to 100.
Hopefully, I am clear enough to get some help from you guys, thanks btw.
Here's my attempt below at trying to maintain and re-use a webdriver internet explorer browser instance:
public class demo extends RemoteWebDriver {
public static WebDriver driver;
public Selenium selenium;
public WebDriverWait wait;
public String propertyFile;
String getSessionId;
public demo() { // constructor
DesiredCapabilities ieCapabilities = DesiredCapabilities
.internetExplorer();
ieCapabilities
.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
driver = new InternetExplorerDriver(ieCapabilities);
this.saveSessionIdToSomeStorage(getSessionId);
this.startSession(ieCapabilities);
driver.manage().window().maximize();
}
#Override
protected void startSession(Capabilities desiredCapabilities) {
String sid = getPreviousSessionIdFromSomeStorage();
if (sid != null) {
setSessionId(sid);
try {
getCurrentUrl();
} catch (WebDriverException e) {
// session is not valid
sid = null;
}
}
if (sid == null) {
super.startSession(desiredCapabilities);
saveSessionIdToSomeStorage(getSessionId().toString());
}
}
private void saveSessionIdToSomeStorage(String session) {
session=((RemoteWebDriver) driver).getSessionId().toString();
}
private String getPreviousSessionIdFromSomeStorage() {
return getSessionId;
}
}
My hope here was that by overriding the startSession() method from remoteWebdriver, it would somehow check that I already had an instance of webdriver browser opened in i.e and it would instead use that instance as opposed to re-creating a new instance everytime I hit that "run" button in eclipse.
I can also see that because I am creating a "new driver instance" from my constructor, since constructor always execute first, it creates that new driver instance automatically, so I might need to alter that somehow, but don't know how.
I am a newbie on both stackoverflow and with selenium webdriver and hope someone here can help.
Thanks!
To answer your question:
No. You can't use a browser that is currently running on your computer. You can use the same browser for the different tests, however, as long as it is on the same execution.
However, it sounds like your real problem is running 100 tests over and over again. I would recommend using a testing framework (like TestNG or JUnit). With these, you can specify which tests you want to run (TestNG will generate an XML file of all of the tests that fail, so when you run it, it will only execute the failed tests).
Actually you can re-use the same session again..
In node client you can use following code to attach to existing selenium session
var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
// The 'capabilities' object as returned by sessionCapabilities
if (err) { /* that session doesn't exist */ }
else {
browser.elementByCss("button.groovy-button", function(err, el) {
...
});
}
});
...
browser.detach();
To get selenium session id,
driver.getSessionId();
Note:
This is available in Node Client only..
To do the same thing in JAVA or C#, you have to override execute method of selenium to capture the sessionId and save it in local file and read it again to attach with existing selenium session
I have tried the below steps to use the same browser instance and it worked for me:
If you are having generic or Class 1 in different package the below code snippet will work -
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
// Class 1 :
public class Generics {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "url";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
// Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
#Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
driver.findElement(By.cssSelector("")).sendKeys("");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
driver.findElement(By.xpath("")).sendKeys("");
}
}
If your Generics class is in the same package you just need to make below change in your code:
public class Generics {
public Generics(){}
WebDriver driver; }
Just remove the protected word from Webdriver code line. Rest code of class 1 remain as it is.
Regards,
Mohit Baluja
I have tried it by extension of classes(Java Inheritance) and creating an xml file. I hope below examples will help:
Class 1 :
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
public class SetUp {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "URL";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import zgenerics.SetUp
public class Conditions extends SetUp {
#Test
public void visible() throws InterruptedException{
Thread.sleep(5000);
boolean signINbutton=driver.findElement(By.xpath("xpath")).isEnabled();
System.out.println(signINbutton);
boolean SIGNTEXT=driver.findElement(By.xpath("xpath")).isDisplayed();
System.out.println(SIGNTEXT);
if (signINbutton==true && SIGNTEXT==true){
System.out.println("Text and button is present");
}
else{
System.out.println("Nothing is visible");
}
}
}
Class 3:
package automationScripts;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
public class Footer extends Conditions {
#Test
public void footerNew () throws InterruptedException{
WebElement aboutUs = driver.findElement(By.cssSelector("CssSelector"));
aboutUs.click();
WebElement cancel = driver.findElement(By.xpath("xpath"));
cancel.click();
Thread.sleep(1000);
WebElement TermsNCond = driver.findElement(By.xpath("xpath"));
TermsNCond.click();
}
}
Now Create an xml file with below code for example and run the testng.xml as testng suite:
copy and paste below code and edit it accordingly.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="classes" thread-count="3">
<test name="PackTest">
<classes>
<class name="automationScripts.Footer"/>
</classes>
This will run above three classes. That means one browser and different tests.
We can set the execution sequence by setting the class names in alphabetical order as i have done in above classes.

Categories

Resources