One browser instance for one suite_Maven+TestNG - selenium

I have sets <test../test> with classes that run in parallel. Now a browser instance is opened for each class. How to open one browser instance per set (eg. for test name="admin") instead of per class?
StudioTests.xml:
suite name="Studio Tests" verbose="1" parallel="tests" thread-count="4"
<parameter name="browser" value="chrome"/>
<test name="admin">
<classes>
<class name="tests.project.Action"/>
<class name="tests.ProjectTransform"/>
</classes>
</test>
<test name="superuser">
<classes>
<class name="tests.Auth"/>
<class name="tests.project.Action"/>
</classes>
</test>
public class BaseTest:
#BeforeClass (alwaysRun = true)
public void setUpMain() {
if (System.getProperty("os.name").toLowerCase().contains("win")) {
driverPath = "src/test/resources/chromedriver102.exe";
}
else {
driverPath = "src/test/resources/chromedriverlinux102";
}
System.setProperty("webdriver.chrome.driver", driverPath);
LoggingPreferences logs = new LoggingPreferences();
logs.enable(LogType.BROWSER, Level.SEVERE);
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromePref = new HashMap<>();
chromePref.put("profile.default_content_settings.popups", 0);
chromePref.put("download.default_directory", System.getProperty("user.dir"));
options.setExperimentalOption("prefs", chromePref);
options.addArguments("headless");
options.addArguments("window-size=1800,1000");
options.setCapability(CapabilityType.LOGGING_PREFS, logs);
options.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10L, SECONDS);
driver.get(System.getProperty("studio_url"));
}
#BeforeClass (alwaysRun = true)
public void setWaiter () {
driver.manage().timeouts().implicitlyWait(10L, SECONDS);
}
#AfterClass(alwaysRun = true)
public void closeBrowser(){
driver.quit();
}

Related

Selenium Grid parallel execution only run few test cases on the docker chrome nodes

Right now i have 80 test method (#Test) using data provider I am running my test case and its almost 400 test cases. When I run it in selenium grid parallel then it only run few test case. Some times 40 some time 50 randomly its running
Here is my Base class
public class BaseTest {
private static final String OS = System.getProperty("os.name").toLowerCase();
public static boolean IS_WINDOWS = (OS.indexOf("win") >= 0);
public WebDriver driver;
String report = null;
public WebDriver getDriver() {
return driver;
}
#BeforeClass(alwaysRun = true)
public void classLevelSetup() throws InterruptedException {
//Did nothing
}
#BeforeMethod(alwaysRun = true)
public void methodLevelSetup() throws ParseException, MalformedURLException {
Log.info("Tests are starting!");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--disable-gpu");
chromeOptions.addArguments("--disable-extensions");
chromeOptions.addArguments("disable-infobars");
chromeOptions.addArguments("--disable-dev-shm-usage");
chromeOptions.addArguments("ignore-certificate-errors");
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
chromeOptions.addArguments("--start-maximized");
driver=new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"),chromeOptions);
// Added Browser
}
#AfterMethod(alwaysRun = true)
public void AfterMethod(ITestResult result, ITestContext ctx)
{
getTest().fail(result.getThrowable());
driver.quit();
}
#AfterClass(alwaysRun = true)
public void teardown() {
//Did nothing
}
Here is my test class
public class DashboardTest extends BaseTest {
#DataProvider(name = "CreateProperty")
public Object[][] getData() {
Object[][] data = SiteConfig.CreateProperty;
return data;
}
#Test(priority = 0, alwaysRun = true, dataProvider = "CreateProperty", description = "Add new property from Management > Properties")
public void Add_new_Property_from_management_Properties(String url, String username, String password, Method method, ITestContext ctx) throws Exception {
SignupPage sp = new SignupPage(driver);
sp.Open_login_Page(url);
}
}
Here is my testng.xml file
<?xml version="1.0" encoding="UTF-8"?>
<test name="CultBooking">
<classes>
<class name="tests.RoomTypeTest"></class>
<class name="tests.RoomTypeTest_1"></class>
<class name="tests.RoomTypeTest_2"></class>
<class name="tests.RoomTypeTest_3"></class>
<class name="tests.RoomValidatyApiResponseTest"></class>
<class name="tests.MealPlanTest"></class>
<class name="tests.MealPlanTest_1"></class>
<class name="tests.MasterdataTest"></class>
<class name="tests.DescriptionsTest"></class>
<class name="tests.SignupTest"></class>
<class name="tests.Reservation_processTest"></class>
<class name="tests.SignInTest"></class>
<class name="tests.DashboardTest"></class>
<class name="tests.ForgotPasswordTest"></class>
</classes>
</test>
**I am running everything in jenkins and here is the error I getting sometimes**
Command: [54f8c566912260f004c50d969fb3fbb8, screenshot {}]
Capabilities {acceptInsecureCerts: false, browserName: chrome,
browserVersion: 96.0.4664.45, chrome: {chromedriverVersion:
96.0.4664.45 (76e4c1bb2ab46..., userDataDir: /tmp/.com.google.Chrome.DIPhAl}, goog:chromeOptions: {debuggerAddress:
localhost:36179}, javascriptEnabled: true, networkConnectionEnabled:
false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX,
proxy: Proxy(), se:cdp: ws://172.19.0.4:4444/sessio..., se:cdpVersion:
96.0.4664.45, se:vnc: ws://172.19.0.4:4444/sessio..., se:vncEnabled: true, se:vncLocalAddress: ws://172.19.0.4:7900, setWindowRect: true,
strictFileInteractability: false, timeouts: {implicit: 0, pageLoad:
300000, script: 30000}, unhandledPromptBehavior: dismiss and notify,
webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true,
webauthn:virtualAuthenticators: true} Session ID:
54f8c566912260f004c50d969fb3fbb8 at
jdk.internal.reflect.GeneratedConstructorAccessor27.newInstance(Unknown
Source) at
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at
org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:200)
at
org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:133)
at
org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:53)
at
org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:184)
at
org.openqa.selenium.remote.TracedCommandExecutor.execute(TracedCommandExecutor.java:50)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:559)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:614)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:618)
at
org.openqa.selenium.remote.RemoteWebDriver.getScreenshotAs(RemoteWebDriver.java:349)
at
utils.listeners.TestListener.saveScreenshotPNG(TestListener.java:39)
at utils.listeners.TestListener.onTestFailure(TestListener.java:78)
at
org.testng.internal.TestListenerHelper.runTestListeners(TestListenerHelper.java:96)
at
org.testng.internal.TestInvoker.runTestResultListener(TestInvoker.java:219)
at
org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:834)
at
org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
Can anyone help me to solve this problem?
If the total test-cases count does not match the expected, it could be because of an exception in some testNG-lifecycle code.
First of all, I'm talking about listeners.
I see utils.listeners.TestListener in stacktrace.
saveScreenshotPNG produces some exception.
Make sure, all of its methods will not throw any exception.
Surround all the code in try-catch, since TestNG is not able to handle exceptions in listeners accurately.
Another question, why sometimes the exception happens in saveScreenshotPNG.
But anyway, try to make fail-safe utils.listeners.TestListener first.

How to run the testng test methods parallel?

I am trying to run the test methods in parallel by using TestNg concept, but it's not working as expected. It's launching multiple browsers and creating each thread for each browser, but it's entering all the value in only one browser. Please help me out. Here browser object and extent reports object are thread safe. Please find the test methods.
This is the Test class that needs to be executed in parallel, but it's not working. It just launches multiple browsers and all the thread value feeding data to one browser itself.
package com.sonata.tests;
import java.util.Map;
import java.util.Properties;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.sonata.utility.DataReader;
import com.sonata.utility.DriverCreation;
import com.sonata.pages.ComplaintPage;
import com.sonata.pages.HomePage;
import com.sonata.pages.LoginPage;
public class ComplainTest extends DriverCreation {
private String browser;
private String url;
HomePage homeObject;
LoginPage loginObject;
ComplaintPage compObject;
DataReader dataReader = new DataReader();
#Parameters({ "url", "browser" })
#BeforeMethod
public void readProperties(String url, String browser) {
/*
* Properties prop = PropertiesReader.getProperty(); browser =
* prop.getProperty("browser.name"); url = prop.getProperty("app.url");
*/
this.browser = browser;
this.url = url;
}
#Test
public void createComplaintCaseWithDefault() {
setTestCaseName("TC-10672");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.createCase(testDataMap.get("ComplaintType"),
testDataMap.get("CustomerName"),
testDataMap.get("ComplaintCategory"));
compObject.complaintPageVerification();
}
}
#Test
public void createComplaintCaseWithSensitive() {
setTestCaseName("TC-10692");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.createCase(testDataMap.get("ComplaintType"),
testDataMap.get("CustomerName"),
testDataMap.get("ComplaintCategory"));
compObject.complaintPageVerification();
}
}
#Test
public void reopenComplaintFieldVerfication() {
setTestCaseName("TC-10958");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.reopenReasonFieldVerification(testDataMap
.get("ComplaintID"));
}
}
#AfterMethod
public void closeBrowser() {
if (driver != null) {
homeObject.tearDownTest();
}
if (report != null) {
report.endTest();
}
}
}
This is the Driver class which will create the driver instance for each Test method.
package com.sonata.utility;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.LogStatus;
import com.sonata.constants.Constants;
public class DriverCreation {
public ExtentReports report;
public WebDriver driver;
public DesiredCapabilities cap1;
public WebDriverWait wait;
protected String testCaseName;
ExtentReport extent;
public Logger logger = Logger.getLogger(this.getClass().toString());
public ExcelReader xlsReader = new ExcelReader(getProjectPath()
+ Constants.XLS_FILE_PATH);
/*
* public DriverCreation(String browser,ExtentReports report,Logger logger){
* this.browser = browser; this.report = report; this.logger = logger; }
*/
public void initExtent(String reportName) {
extent = new ExtentReport();
report = extent.getExtentReportInstance(reportName);
}
public void setTestCaseName(String testCaseName){
this.testCaseName = testCaseName;
}
public WebDriver initDriver(String browser) {
try {
cap1 = new DesiredCapabilities();
if (!Constants.CONSTANTS_GRIDEXECUTION) {
if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver",
Constants.CONSTANTS_GECKO_DRIVER_PATH);
cap1.setCapability("marionette", true);
/* ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new FirefoxDriver(cap1);
}
};*/
//driver = driver1.get();*/
driver= new FirefoxDriver(cap1);
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, "Firefox driver has started");
logger.info("Firefox driver has started");
} else if (browser.equalsIgnoreCase("Chrome")) {
System.setProperty(Constants.CONSTANTS_CHROME_PROPERTY,
Constants.CONSTANTS_CHROME_DRIVER_PATH);
/*driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new ChromeDriver();
}
};
driver = driver1.get();*/
driver = new ChromeDriver();
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, "Chrome driver has started");
logger.info("Chrome driver has started");
} else if (browser.equalsIgnoreCase("PhantomJS")) {
System.setProperty(Constants.CONSTANTS_PHANTOM_PROPERTY,
Constants.CONSTANTS_PHANTOM_DRIVER_PATH);
cap1.setJavascriptEnabled(true);
cap1.setCapability("takesScreenshot", true);
cap1.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
Constants.CONSTANTS_PHANTOM_DRIVER_PATH);
/*ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new PhantomJSDriver(cap1);
}
};
driver = driver1.get();*/
driver = new PhantomJSDriver(cap1);
driver.manage().window().setSize(new Dimension(1920, 1200));
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO,
"PhantomJS/Ghost driver has started");
logger.info("PhantomJS/Ghost driver has started");
} else if (browser.equalsIgnoreCase("IE")) {
System.setProperty(Constants.CONSTANTS_IE_PROPERTY,
Constants.CONSTANTS_IE_DRIVER_PATH);
// cap1.internetExplorer();
cap1.setCapability(
InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION,
true);
/*ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new InternetExplorerDriver(cap1);
}
};
driver = driver1.get();*/
driver = new InternetExplorerDriver(cap1);
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO,
"Internet Explorer driver has started");
logger.info("Internet Explorer driver has started");
}
} else {
String nodeUrl = Constants.CONSTANTS_IPDETAILS;
if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver",
Constants.CONSTANTS_GECKO_DRIVER_PATH);
cap1.setCapability("marionette", true);
cap1 = DesiredCapabilities.firefox();
cap1.setBrowserName("firefox");
cap1.setPlatform(Platform.WINDOWS);
} else if (browser.equalsIgnoreCase("Chrome")) {
System.setProperty(Constants.CONSTANTS_CHROME_PROPERTY,
Constants.CONSTANTS_CHROME_DRIVER_PATH);
cap1 = DesiredCapabilities.chrome();
cap1.setBrowserName("chrome");
cap1.setPlatform(Platform.WINDOWS);
} else if (browser.equalsIgnoreCase("IE")) {
System.setProperty(Constants.CONSTANTS_IE_PROPERTY,
Constants.CONSTANTS_IE_DRIVER_PATH);
// cap1.internetExplorer();
cap1 = DesiredCapabilities.internetExplorer();
cap1.setBrowserName("internet explorer");
cap1.setPlatform(Platform.WINDOWS);
cap1.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
cap1.setCapability(
InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION,
true);
}
ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
try {
return new RemoteWebDriver(new URL(nodeUrl), cap1);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
};
driver = driver1.get();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, browser + " driver has started");
logger.info(browser + " driver has started");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Assert.assertTrue(true, "Set up Test");
} catch (Exception e) {
logger.error("Try and catch block while assert " + e);
}
}
return driver;
}
private String getProjectPath() {
File currentDirFile = new File("");
String path = currentDirFile.getAbsolutePath();
return path;
}
}
TESTNG SUITE XML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="C4C" thread-count="3" parallel="methods">
<parameter name="url" value="https://abc.xyz.ondemand.com/"/>
<parameter name="browser" value="Chrome"/>
<test name="Case" allow-return-values="true" group-by-instances="true">
<classes>
<class name="com.sonata.tests.ComplainTest" >
</class>
</classes>
</test>
</suite>
You are storing the driver at class level. But you parallelise based on methods. In this case one driver object will be there. I see the thread local lines were commented.
There are two ways to solve this issue,
One: As your running in method level and navigating the HomePage in each method, you can maintain driver object in method level,
Webdriver driver = initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
Other way: you can maintain the driver object in thread local in your driver creation class,
public class DriverCreation {
private static ThreadLocal<WebDriver> WEBDRIVER = new ThreadLocal<WebDriver>();
public WebDriver getWebDriver(String browser){
WebDriver driver= WEBDRIVER.get();
if (driver== null) {
driver = initDriver(browser);
WEBDRIVER.set(driver);
}
return driver;
}
}
And use it in test method in same way,
Webdriver driver = getWebDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
The second one will create only one driver per thread while first one will create one driver per method. Handle the driver quit accordingly

Parallel execution is not working for attribute tests in testng.xml

Parallel execution is not working for attribute "tests" in suite.xml. Even though I have set parallel ="tests", it is still executing in sequential order only.
Please find below my suite.xml and the test script
suite.xml:
<suite name="testsuite1" parallel="tests" thread-count="2">
<test name="gmailloginchrome">
<parameter name="platform" value="windows"></parameter>
<parameter name="browser" value="chrome"></parameter>
<classes>
<class name="sample.LoginChrome"></class>
</classes>
</test>
<test name="gmailloginie">
<parameter name="platform" value="windows"></parameter>
<parameter name="browser" value="ie"></parameter>
<classes>
<class name="sample.LoginChrome"></class>
</classes>
</test>
</suite>
My Test Script :
package sample;
public class LoginChrome {
WebDriver driver;
Logger log = Logger.getLogger(LoginChrome.class);
/**
* tests the login of Gmail for given credentials in Chrome
* #throws Exception
*/
#Test
public void loginTest() throws Exception {
System.out.println("Inside the test method");
log.info("started the test method");
log.info("entering credentials");
driver.findElement(By.id("identifierId")).clear();
driver.findElement(By.id("identifierId")).sendKeys("xyz#gmail.com");
driver.findElement(By.id("identifierNext")).click();
driver.findElement(By.name("password")).sendKeys("abc#2016");
Thread.sleep(3000);
driver.findElement(By.cssSelector("div#passwordNext")).click();
Thread.sleep(6000);
log.info("checking whether login successful or not");
String title = driver.getTitle();
log.info("Title is " + title);
Thread.sleep(3000);
Assert.assertEquals(title, "Inbox (7,258) - xyz#gmail.com - Gmail");
log.info("completed the test method");
}
/**
* sets the driver executable and opens the browser
* #param platform
* #param browser
* #return nothing
*/
#Parameters({ "platform", "browser" })
#BeforeMethod
public void beforeMethod(String platform, String browser) {
if(browser.contains("chrome")) {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/drivers/chromedriver.exe");
driver = new ChromeDriver();
}
else if(browser.contains("ie")) {
System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") + "/drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://www.gmail.com");
}
/**
* quits the driver & closes the browser
* #return nothing
*/
#AfterMethod
public void afterMethod() {
driver.quit();
}
}
I got the issue. It's because of TestNG version. If I use TestNG -6.9.10, same code is working fine. There is nothing wrong in the code.

I can't run my .bat file,but i can run my .xml file.How i will run that .bat file?

-This is a simple java project.
-I used Testng in it.
-When I run my .xml file by Testng then, I can see my script has run on the remote machines.
-but when I create the .bat file, then that has not executed.
-I am using selenium grid with Jenkins.So, please share a code on it.
Showing error message on my cmd window like these:-
set classpath=D:\selenium\selenium_grid\bin;D:\selenium\selenium_grid\lib\*
new chrome options<> is preferred to DesiredCapabilities capabilities=DesiredCapabilities.chrome();
Code :
package grid_hub_node;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class Demo {
WebDriver driver;
#Parameters({ "system" })
#Test
public void testdemo(String system) throws InterruptedException
{
if (system.equalsIgnoreCase("pc1")) {
try {
String nodeurl;
nodeurl="http://192.168.1.115:5090/wd/hub";
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
capabilities.setPlatform(Platform.WIN10);
driver=new RemoteWebDriver(new URL(nodeurl),capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
driver.get("https://www.ebay.in/");
String title_name=driver.getTitle();
System.out.println(title_name);
Thread.sleep(7000l);
driver.quit();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}}
else if (system.equalsIgnoreCase("pc2")) {
try {
String nodeurl;
nodeurl="http://192.168.1.112:6760/wd/hub";
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
capabilities.setPlatform(Platform.WIN10);
driver=new RemoteWebDriver(new URL(nodeurl),capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
driver.get("http://sdrc.co.in/");
String title_name=driver.getTitle();
System.out.println(title_name);
Thread.sleep(7000l);
driver.quit();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}}
else if (system.equalsIgnoreCase("pc3")) {
try {
String nodeurl;
nodeurl="http://192.168.1.102:4051/wd/hub";
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
capabilities.setPlatform(Platform.WIN10);
driver=new RemoteWebDriver(new URL(nodeurl),capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
driver.get("http://www.seleniumhq.org/");
String title_name=driver.getTitle();
System.out.println(title_name);
Thread.sleep(7000l);
driver.quit();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}}
else if (system.equalsIgnoreCase("pc4")) {
try {
String nodeurl;
nodeurl="http://192.168.1.121:7611/wd/hub";
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
capabilities.setPlatform(Platform.WIN10);
driver=new RemoteWebDriver(new URL(nodeurl),capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
driver.get("https://www.microsoft.com/net/download/windows");
String title_name=driver.getTitle();
System.out.println(title_name);
Thread.sleep(7000l);
driver.quit();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}}
else if (system.equalsIgnoreCase("pc5")) {
try {
String nodeurl;
nodeurl="http://192.168.1.177:6474/wd/hub";
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
capabilities.setPlatform(Platform.WIN10);
driver=new RemoteWebDriver(new URL(nodeurl),capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
driver.get("https://cricket.yahoo.com/");
String title_name=driver.getTitle();
System.out.println(title_name);
Thread.sleep(7000l);
driver.quit();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}}
else if (system.equalsIgnoreCase("pc6")) {
try {
String nodeurl;
nodeurl="http://192.168.1.141:5871/wd/hub";
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
capabilities.setPlatform(Platform.WIN10);
driver=new RemoteWebDriver(new URL(nodeurl),capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
driver.get("http://www.fifa.com/");
String title_name=driver.getTitle();
System.out.println(title_name);
Thread.sleep(7000l);
driver.quit();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}}}}
TestNG.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" thread-count="10" parallel="tests">
<test name="Test1">
<parameter name="system" value="pc1"/>
<classes>
<class name="grid_hub_node.Grid_Demo_parallel"/>
</classes>
</test>
<test name="Test2">
<parameter name="system" value="pc2"/>
<classes>
<class name="grid_hub_node.Grid_Demo_parallel"/>
</classes>
</test>
<test name="Test3">
<parameter name="system" value="pc3"/>
<classes>
<class name="grid_hub_node.Grid_Demo_parallel"/>
</classes>
</test>
<test name="Test4">
<parameter name="system" value="pc4"/>
<classes>
<class name="grid_hub_node.Grid_Demo_parallel"/>
</classes>
</test>
<test name="Test5">
<parameter name="system" value="pc5"/>
<classes>
<class name="grid_hub_node.Grid_Demo_parallel"/>
</classes>
</test>
<test name="Test6">
<parameter name="system" value="pc6"/>
<classes>
<class name="grid_hub_node.Grid_Demo_parallel"/>
</classes>
</test>
</suite> <!-- Suite -->
bat file :
set projectLocation=D:\selenium\selenium_grid
cd %projectLocation%
set classpath=%projectLocation%\bin;%projectLocation%\lib\*
java org.testng.TestNG %projectLocation%\testng.xml
pause
The error gives us some hint about the issues as follows :
set classpath=D:\selenium\selenium_grid\bin;D:\selenium\selenium_grid\lib\*
new chrome options<> is preferred to DesiredCapabilities capabilities=DesiredCapabilities.chrome();
The main issue seems to be in Setting the classpath
Solution
Follow the steps :
Get project location from your IDE (e.g. Eclipse), go to the location on your system, create a directory "lib"
Dump all the libraries (Selenium jars, TestNG) in the "lib" directory.
From the Project Directory, through CLIP provide the following classpath:
C:\Users\<user_name>\<ProjectWorkspace>\<ProjectName>>set classpath=C:\Users\<user_name>\<ProjectWorkspace>\<ProjectName>\bin;C:\<user_name>\<ProjectWorkspace>\<ProjectName>\lib\*;
Execute testng.xml from the CLI as follows:
C:\<user_name>\<ProjectWorkspace>\<ProjectName>>java org.testng.TestNG testng.xml
Observe the Testcase gets executed.
Within the create a new text document and add the following code:
java -cp bin;lib/* org.testng.TestNG testng.xml
Save as "run.bat"
Execute the script & verify Testcase gets executed.

One selenium test (using testng) executes AfterSuite method, another test case does not

I have come across a situation where one Selenium test does execute #AfterSuite block, while the other does not.
I am running both the test using testng.xml.
Initially I thought there might be some config issue in testng.xml; but I closed down the issue to test case level and my intuition says there is something which I am missing in test case level.
My #AfterSuite block is actually responsible for sending email after the test execution is over, so it is part of a different package in my project; and not in Test Case level.
Here is the test case which does execute the #AfterSuite :
package unitTest;
/*import statements*/
public class OpenBrowser extends ExtentReport {
#Test
public void launch() throws IOException, InterruptedException {
test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser();
System.out.println(ReadExcelData.readExcelData("Login.xlsx", 0, 0, 0));
Login.LoginField(Base.driver).sendKeys(ReadExcelData.readExcelData("Login.xlsx", 0, 1, 0));
Login.PasswordField(Base.driver).sendKeys(ReadExcelData.readExcelData("Login.xlsx", 0, 1, 1));
Login.SignIn(Base.driver).click();
}
#AfterTest
public void tearDown()
{
Base.closeBrowser();
}
}
And the Test which does not execute the #AfterSuite block:
package fundSearch;
/* Import Statements*/
public class FundNavigation extends ExtentReport {
#Test
public void verifyFundPage() {
test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser();
Funds.FundsLink(Base.driver).click();
Assert.assertEquals(Funds.SearchFundsField(Base.driver).isDisplayed(), true);
}
#AfterTest
public void tearDown()
{
Base.closeBrowser();
}
}
The ExtentReport.java is below:
package com....core;
/*Import Statements*/
public class ExtentReport {
public static ExtentHtmlReporter htmlReporter;
public static ExtentReports extent;
public static ExtentTest test;
public static String suiteName;
#BeforeSuite
public static void setUp(ITestContext ctx) {
// String currentDate=getDateTime();
suiteName = ctx.getCurrentXmlTest().getSuite().getName();
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir") + "/Reports/" + suiteName + ".html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("OS", "Windows");
extent.setSystemInfo("Host Name", "CI");
extent.setSystemInfo("Environment", "QA");
extent.setSystemInfo("User Name", "QA_User");
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setDocumentTitle("AutomationTesting Report");
htmlReporter.config().setReportName("testReport");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.STANDARD);
}
#AfterMethod
public void getResult(ITestResult result) throws IOException {
if (result.getStatus() == ITestResult.FAILURE) {
String screenShotPath = GetScreenShot.capture(Base.driver, "screenShotName", result);
test.log(Status.FAIL, MarkupHelper.createLabel(result.getName() + " Test case FAILED due to below issues:",
ExtentColor.RED));
test.fail(result.getThrowable());
test.fail("Snapshot below: " + test.addScreenCaptureFromPath(screenShotPath));
} else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(Status.PASS, MarkupHelper.createLabel(result.getName() + " Test Case PASSED", ExtentColor.GREEN));
} else {
test.log(Status.SKIP,
MarkupHelper.createLabel(result.getName() + " Test Case SKIPPED", ExtentColor.ORANGE));
test.skip(result.getThrowable());
}
extent.flush();
}
#AfterSuite
public void tearDown() throws Exception {
System.out.println("In After Suite");
SendEmail.execute(SendEmail.path);
}
public static String getDateTime() {
// Create object of SimpleDateFormat class and decide the format
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// get current date time with Date()
Date date = new Date();
// Now format the date
String currentDate = dateFormat.format(date);
String newDate = currentDate.replace('/', '_');
String newCurrentDate = newDate.replace(':', '.');
return newCurrentDate;
}
}
The SendEmail.java is provided below:
/*Package Statement and Import Statements*/
public class SendEmail {
public static String path=System.getProperty("user.dir")+"/Reports/"+ExtentReport.suiteName+".html";
static String[] to={"xxx"};
static String[] cc={};
static String[] bcc={};
public static void execute(String reportFileName) throws Exception {
SendEmail.sendMail("xxx#gmail.com",
"xxx",
"smtp.gmail.com",
"465",
"true",
"true",
true,
"javax.net.ssl.SSLSocketFactory",
"false",
to,
cc,
bcc,
"Automation report",
System.getProperty("user.dir")+"/Reports/"+ExtentReport.suiteName+".html",
path,
reportFileName);
}
public static boolean sendMail(String userName,
String passWord,
String host,
String port,
String starttls,
String auth,
boolean debug,
String socketFactoryClass,
String fallback,
String[] to,
String[] cc,
String[] bcc,
String subject,
String text,
String attachmentPath,
String attachmentName){
//Object Instantiation of a properties file.
Properties props = new Properties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port)){
props.put("mail.smtp.port", port);
}
if(!"".equals(starttls)){
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
}
if(debug){
props.put("mail.smtp.debug", "true");
}else{
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port)){
props.put("mail.smtp.socketFactory.port", port);
}
if(!"".equals(socketFactoryClass)){
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
}
if(!"".equals(fallback)){
props.put("mail.smtp.socketFactory.fallback", fallback);
}
try{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
msg.setFrom(new InternetAddress(userName));
for(int i=0;i<to.length;i++){
msg.addRecipient(Message.RecipientType.TO, new
InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++){
msg.addRecipient(Message.RecipientType.CC, new
InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++){
msg.addRecipient(Message.RecipientType.BCC, new
InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
} catch (Exception mex){
mex.printStackTrace();
return false;
}
}
}
My testng.xml is defined as below (for the first test):
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="DefaultSuite" >
<!-- <listeners>
<listener class-name="org.uncommons.reportng.HTMLReporter"/>
<listener class-name="org.uncommons.reportng.JUnitXMLReporter"/>
</listeners>-->
<test name="Test" >
<classes>
<class name="unitTest.OpenBrowser" />
</classes>
</test>
</suite>
The testng.xml for the second test is like below.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="DefaultSuite" >
<!-- <listeners>
<listener class-name="org.uncommons.reportng.HTMLReporter"/>
<listener class-name="org.uncommons.reportng.JUnitXMLReporter"/>
</listeners>-->
<test name="Test" >
<classes>
<class name="fundSearch.FundNavigation" />
</classes>
</test>
</suite>
Could any one please point out if I am doing something wrong/difference for which #Aftersuite is running when the first test is executed and not when the second test is run?