Junit 5 tests are not running in parallel - junit5

I have created a simple program to intialte crome and one SYSO statement. I want to run the 2 #Test in parallel. But it is executing alwasy is seq. What could be teh reason for it to not recognise the parallel execution?
Here is the code:
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Proxy.ProxyType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
#Execution(ExecutionMode.CONCURRENT)
public class Parallel {
static String driverPath = "C:/BestX/workspace/chromedriver_win32/chromedriver.exe";
static String downloadFilepath = "C:\\BestX";
#Execution(ExecutionMode.CONCURRENT)
#Test
void test1() throws Exception {
createDriver();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+" => test1"); //.currentThread.getName() -just to display current running thread name
}
#Execution(ExecutionMode.CONCURRENT)
#Test
void test2() throws Exception {
createDriver();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+" => test1"); //.currentThread.getName() -just to display current running thread name
}
public void createDriver() {
DesiredCapabilities dcaps = new DesiredCapabilities();
dcaps.setCapability("takesScreenshot", true);
System.setProperty("webdriver.chrome.driver", driverPath);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments(new String[] { "--no-sandbox" });
chromeOptions.addArguments(new String[] { "--max_old_space_size=4096" });
dcaps.setCapability("goog:chromeOptions", chromeOptions);
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", downloadFilepath);
chromeOptions.setAcceptInsecureCerts(true);
chromeOptions.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().window().setSize(new Dimension(1920, 1200));
}
}
'''
and here is the "junit-platform.properties" under resource folder
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent

It is workign now. Was a silly mistake in folder structure. The junit-platform.properties file was under tests->resources instead of test->resources folder

Related

i need change lenguage of microsoft edge for selenium automation --lang=es

i need change the language to --lang=es in microsoft-edge selenium java.
Because can't the page see in english and need in spanish
Try this code, its working:
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.edge.options import Options
options = Options()
options.add_argument("--lang=es")
options.add_experimental_option('excludeSwitches', ['enable-logging'])
prefs = {"translate_whitelists": {'en':'es'},
"translate":{"enabled":"true"}}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()), options=options)
driver.maximize_window()
driver.get("https://www.microsoft.com")
Based on AbiSaran's answer (which is in Python), I modified it into a Java one.
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.edge.driver", "C:\\path\\to\\msedgedriver.exe");
EdgeOptions options = new EdgeOptions();
options.addArguments("--lang=es");
EdgeDriver driver = new EdgeDriver(options);
try {
driver.get("https://bing.com");
WebElement element = driver.findElement(By.id("sb_form_q"));
element.sendKeys("WebDriver");
element.submit();
Thread.sleep(5000);
} finally {
driver.quit();
}
}
}

Groovy, Selenium, Cucumber, adding ChromeOptions arguments

I wanted to create a BaseTest.groovy where i implement the Webdriver with headless mode.
package api
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
class BaseTest{
ChromeOptions chromeOptions = new ChromeOptions()
chromeOptions.addArguments(["--headless", "--no-sandbox"])
static WebDriver driver = new ChromeDriver(chromeOptions)
}
I have a LoginSteps.groovy stepdefinitions file
package stepDefinitions
import api.Helper.helper
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
import static cucumber.api.groovy.EN.*
Given(~/^I am on the xyz login page$/) { ->
helper.setPage("https://xyzTestpage.com/")
}
When(~/^I sign in as "([^"]*)"$/) { String arg1 ->
helper.signIn("username","password")
}
Then(~/^I load the homepage$/) { ->
helper.setPreset()
}
And i have a helper.groovy file where i implement the methods
package api.Helper
import api.BaseTest
import api.Xpaths.LoginPageXpaths
import api.Tools.tools
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
class helper extends BaseTest {
static void setPage(String url){
driver.get(url)
}
static void signIn(String username, String password){
WebElement uname = driver.findElement(By.xpath(LoginPageXpaths.userNameField()))
uname.sendKeys(username)
WebElement pwd = driver.findElement(By.xpath(LoginPageXpaths.passWordField()))
pwd.sendKeys(password)
WebElement loginButton = driver.findElement(By.xpath(LoginPageXpaths.loginButton()))
loginButton.click()
}
static void setPreset(){
WebElement multiCountry = driver.findElement(By.xpath(LoginPageXpaths.multiCountryButton()))
multiCountry.click()
WebElement openButton = driver.findElement(By.xpath(LoginPageXpaths.openButton()))
openButton.click()
String inputWindow = driver.getWindowHandle()
for(String loggedInWindow : driver.getWindowHandles()){
driver.switchTo().window(loggedInWindow)
}
WebElement lineItem = driver.findElement(By.xpath(LoginPageXpaths.calculateButtonXpath()))
tools.waitForElementToBeClickable(driver,lineItem,25)
driver.quit()
}
}
So my problem is, i don't know where should i set the headless mode, because i got error, when i run this.
Can you please try adding arguments separately as below and run it
class BaseTest{
ChromeOptions chromeOptions = new ChromeOptions()
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--no-sandbox");
static WebDriver driver = new ChromeDriver(chromeOptions)
}

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

Trying to run an eclipse JAVA program in Sauce Labs. But getting an issue with constructor and remote webdriver.

Written below code to run an eclipse program in Sauce Labs. Workflow is showing an issue "The constructor Remote WebDriver(String, DesiredCapabilities) is undefined".
Still I tried to run the program then below issue came.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor RemoteWebDriver(URL, DesiredCapabilities) is undefined
The constructor URL(String) is undefined at sauceprog.main(sauceprog.java:40)
CODE:
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.gargoylesoftware.htmlunit.javascript.host.URL;
public class sauceprog
{
public static void main(String[] args) throws InterruptedException, MalformedURLException
{
String browser = "safari-saucelabs";
String URL = "https://rpautomation4:27763475-7193-4984-8074-a4fe2f9982f7#ondemand.saucelabs.com:443/wd/hub";
DesiredCapabilities caps = null;
switch(browser.toLowerCase())
{
case "internetexplorer-win-saucelabs":
caps = DesiredCapabilities.internetExplorer();
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "11.103");
caps.setCapability("recordVideo", "false");
caps.setCapability("screenResolution", "1024x768");
break;
case "chrome-win-saucelabs":
caps = DesiredCapabilities.chrome();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "69.0");
caps.setCapability("recordVideo", "false");
break;
case "firefox-win-saucelabs":
caps = DesiredCapabilities.firefox();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "62.0");
caps.setCapability("recordVideo", "false");
default:
System.out.println("you passed incorrect values. Please check next time");
}
RemoteWebDriver driver = new RemoteWebDriver(URL,caps);
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("selenium");
Thread.sleep(2000);
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
driver.quit();
}
}
You are using an incorrect import statement. Ideally, your program should use import java.net.URL; instead of import com.gargoylesoftware.htmlunit.javascript.host.URL;
I have posted the complete updated code snippet below:
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
public class sauceprog
{
public static void main(String[] args) throws InterruptedException, MalformedURLException
{
String browser = "safari-saucelabs";
String URL = "https://<sauce_user>:<key>#ondemand.saucelabs.com:443/wd/hub";
DesiredCapabilities caps = null;
switch(browser.toLowerCase())
{
case "internetexplorer-win-saucelabs":
caps = DesiredCapabilities.internetExplorer();
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "11.103");
caps.setCapability("recordVideo", "false");
caps.setCapability("screenResolution", "1024x768");
break;
case "chrome-win-saucelabs":
caps = DesiredCapabilities.chrome();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "69.0");
caps.setCapability("recordVideo", "false");
break;
case "firefox-win-saucelabs":
caps = DesiredCapabilities.firefox();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "62.0");
caps.setCapability("recordVideo", "false");
default:
System.out.println("you passed incorrect values. Please check next time");
}
RemoteWebDriver driver = new RemoteWebDriver(new URL(URL),caps);
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("selenium");
Thread.sleep(2000);
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
driver.quit();
}
}
Also, I would suggest you update your sauce username and key if not already done. Since you posted the username and key publicly, anyone can run their tests on your account using the same.

Selenium tests for custom portlets

Can anyone provide me a link/document with information on how to write and test custom liferay portlets with Selenium.
I am using Liferay 6.1EE
Thanks
Same as with other tests, assuming you want to run as JUnit test
package org.ood.selenium.test;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.IncorrectnessListener;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptErrorListener;
import com.thoughtworks.selenium.SeleneseTestBase;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.regex.Pattern;
public class MyTest extends SeleneseTestBase {
WebDriver driver =null;
#Before
public void setUp() throws Exception {
DesiredCapabilities dc = DesiredCapabilities.firefox();
// dc.setCapability(FirefoxDriver.BINARY, new
//File("C:/Program Files (x86)/Mozilla Firefox/firefox.exe").getAbsolutePath());
dc.setJavascriptEnabled(true);
// driver= new HtmlUnitDriver(true);//Not properly working
driver = new FirefoxDriver(dc);
String baseUrl = "http://localhost:8080/web/guest/home";
selenium = new WebDriverBackedSelenium(driver, baseUrl);
}
/* #Test
public void homePage() throws Exception {
final WebClient webClient = new WebClient();
//HTMLUNit throws lots of errors
webClient.setJavaScriptEnabled(true);
webClient.setJavaScriptErrorListener(new JavaScriptErrorListener() {
public void timeoutError(HtmlPage htmlPage, long allowedTime,
long executionTime) {
// TODO Auto-generated method stub
}
public void scriptException(HtmlPage htmlPage,
ScriptException scriptException) {
System.out.println(scriptException.getMessage());
}
public void malformedScriptURL(HtmlPage htmlPage, String url,
MalformedURLException malformedURLException) {
System.out.println(url);
}
public void loadScriptError(HtmlPage htmlPage, URL scriptUrl,
Exception exception) {
// TODO Auto-generated method stub
}
});
//webClient.setThrowExceptionOnFailingStatusCode(false);
webClient.setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://localhost:8080/web/guest/home");
webClient.getCache().clear();
page.getElementById("sign-in").click();
page.getElementById("_58_login").type("test#liferay.com");
page.getElementById("_58_password").type("test#liferay.com");
final HtmlButton submit = (HtmlButton)page.getByXPath("//input").get(0);
submit.click();
//assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
System.out.println("Title= " +page.getTitleText());
final String pageAsXml = page.asXml();
// assertTrue(pageAsXml.contains("<body class=\"composite\">"));
System.out.println("pageAsXml=" +pageAsXml);
final String pageAsText = page.asText();
//assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
System.out.println("pageAsText="+pageAsText);
webClient.closeAllWindows();
}*/
#Test //Using Graphical GUI
public void testMytest() throws Exception {
//driver.get("http://localhost:8080/web/guest/home");
selenium.open("/");
//selenium.click("id=sign-in");
driver.findElement(By.id("sign-in")).click();
driver.findElement(By.name("_58_login")).clear();
driver.findElement(By.name("_58_login")).sendKeys("test#liferay.com");
driver.findElement(By.name("_58_password")).sendKeys("123");
//driver.findElement(By.name("_58_login")).sendKeys("test#nsn.com");
//driver.findElement(By.name("_58_password")).sendKeys("test");
driver.findElement(By.className("aui-button-input-submit")).submit();
//selenium.setSpeed("1000");
//selenium.waitForPageToLoad("5000");
//Select a nested div( the NodeTree)
driver.findElement(By.xpath("//div[contains(#class,'aui-tree-node-content')" +
" and (contains(.,'TreeNodeX'))]//div[contains(#class,'aui-tree-hitarea')]"))
.click();
//selenium.captureScreenshot("d:/_del/sel_screen.png");//this throws an error
//workaround
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("d:/_del/sel_screen.png"));
System.out.println("Bodytex=[" +selenium.getBodyText() +"]End Body Text");
String[] titles= selenium.getAllWindowTitles();
System.out.println("Titles Start-");
for (int i = 0; i < titles.length; i++) {
System.out.println(titles[i]);
}
System.out.println("Titles End");
verifyEquals(true, selenium.getBodyText().contains("Site View"));
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}