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)
}
Related
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();
}
}
}
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
I'm trying to test Resizable in chrome using Actions.dragAndDropBy, but not working.
My code is
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://jqueryui.com/resizable/");
driver.switchTo().frame(driver.findElement(By.className("demo-frame")));
Actions act = new Actions(driver);
WebElement element = driver.findElement(By.xpath(".// [#id='resizable']/div[3]"));
Thread.sleep(3000);
act.dragAndDropBy(element, 100, 100).build().perform();
driver.close();
I tried below also Actions.clickAndHold(WebElement) method also as below
Actions act = new Actions(driver);
act.clickAndHold(element).moveByOffset(100,100).release().build().perform();
What am I doing wrong here ?
To resize the Resizable element in Chrome using Actions class and dragAndDropBy() method you can use the following solution:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class DragDrop_Resizable {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
WebDriver driver = new ChromeDriver(options);
driver.get("http://jqueryui.com/resizable/");
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.className("demo-frame")));
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se']")));
new Actions(driver).dragAndDropBy(element, 100, 100).build().perform();
}
}
Original Element Snapshot:
Resized Element Snapshot:
I have 2 step definition files/2 feature file run by a runner file. When I run the script, it is opening 2 browsers every time. Not sure what I am doing wrong. My runner file is as follows
package KohlsLoginTest;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(plugin = { "html:target/cucumber-html-report",
"pretty:target/cucumber-pretty.txt",
"junit:target/cucumber-results.xml" },
features = { "./src/test/resources/Features" },
tags = { "#SmokeTest" }
)
public class kohlsLoginRunner {
}
My step def file is as below, I have a #before and #after hooks, the complaint is about the #before hook. I don't know how to figure it out.
public class kohlsLoginTest {
WebDriver driver = new ChromeDriver();
#Before
public void before() throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:\\Software\\Drivers\\chromedriver.exe");
driver.manage().deleteAllCookies();
//Navigate to the sign in screen
driver.navigate().to("https://www.kohls.com");
Thread.sleep(4000);
WebElement account = driver.findElement(By.xpath("//*
[#id=\"utility-nav\"]/ul/li[1]/div[1]/a"));
account.click();
WebElement signin = driver.findElement(By.xpath("//*
[#id=\"pb_signin\"]/div"));
signin.click();
}
My file structure in Eclipse is as follows:
I am a newbie to selenium testing.
Basically,
I have a selenium class like :
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import java.awt.AWTException;
import java.awt.Robot;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTests {
public void commonFunction(){
System.setProperty("webdriver.chrome.driver", "C://Downloads//chromedriver_win32//chromedriver.exe");
WebDriver driver = new ChromeDriver();
Actions builder = new Actions(driver);
driver.get("http://localhost:3000");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
test1(driver,builder);
}
//The driver,builder will be used by all the below 3 test functions.
/**
* Calling the Most Visited API -- TEST1
*/
public void test1(WebDriver driver,Actions builder){
WebElement most_visited_link = driver.findElement(By.id("mostVisited"));
Thread.sleep(2000);
Action mouseOvermost_visited_link = builder.moveToElement(most_visited_link).build();
mouseOvermost_visited_link.perform();
Thread.sleep(2000);
driver.findElement(By.id("mostVisited")).click();
Thread.sleep(1000);
WebElement most_Visited_button = driver.findElement(By.id("datePicked"));
Action mouse_most_VisitedOverDatePicker = builder.moveToElement(most_Visited_button).build();
mouse_most_VisitedOverDatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
test2(driver,builder);
}
/**
* Calling the Status Pie API -- TEST2
* #param builder
* #param driver
*/
public void test2(WebDriver driver,Actions builder){
WebElement status_pie_link = driver.findElement(By.id("statusPie"));
Thread.sleep(2000);
//Actions builder = new Actions(driver);
Action mouseOverStatusPie = builder.moveToElement(status_pie_link).build();
mouseOverStatusPie.perform();
Thread.sleep(1000);
driver.findElement(By.id("statusPie")).click();
Thread.sleep(1000);
WebElement status_pie_button = driver.findElement(By.id("datePicked"));
Action mouseOver_Status_pie_DatePicker = builder.moveToElement(status_pie_button).build();
mouseOver_Status_pie_DatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
test3(driver,builder);
}
/**
* Calling the Old Data API -- TEST3
*/
public void test2(WebDriver driver,Actions builder){
WebElement old_data_link = driver.findElement(By.id("oldData"));
Thread.sleep(2000);
// Actions builder = new Actions(driver);
Action mouseOverOldData = builder.moveToElement(old_data_link).build();
mouseOverOldData.perform();
Thread.sleep(2000);
driver.findElement(By.id("oldData")).click();
Thread.sleep(1000);
WebElement old_data_button = driver.findElement(By.id("datePicked"));
Action mouseOverDatePicker = builder.moveToElement(old_data_button).build();
mouseOverDatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
driver.quit();
}
}
The code executes as expected on the browser and closes the chrome window.
However, in the index report, I see log as :
3 methods, 2 skipped, 1 passed
Skipped methods :
mostVisitedfunction
statuspiefunction
Passed methods :
createConnection
Any idea where am I going wrong ?
Thanks in advance.
The method mostVisitedfunction should not have annotation because it is the helping method for yoyr test case. Instead create a new class, create a object of the same in the #test class and then call that method..
See the below example..
My test is
//MAximize the Screen
driver.manage().window().maximize();
//Go to Gmail Login Page
SignInPage SignInPage = WebUtils.GoToSignInPage(driver);
//Sign in to Login page -Send Username
SignInPage.SendkeysMethodForSignInPAge(driver, By.cssSelector("input[id='Email']") , "kishanpatelllll.8#gmail.com" );
//Click on Next
SignInPage.ClickToLogin(driver, By.cssSelector("input[id='next']"));
//Wait for password field to be visible
SignInPage.WaitForElementTobeVisible(driver, By.cssSelector("input[id='Passwd'][type='password']"));
So when i call the method SendkeysMethodForSignInPAge i wont write it in #Test.
See SendkeysMethodForSignInPAge method:
public class SignInPage {
public void SendkeysMethodForSignInPAge(WebDriver driver, By by, String s) {
WebUtils.Sendkeys(driver,by,s);
}
I created a new class and there i defined it.
This is basic flow.
Hope you can relate this.
Reply to me, if your are still stuck.
Happy Learning :-)
The error comes because if you have parameters in your #Test annotated method, then those need to come from #Parameters or #DataProvider. Else, if none of the annotation supplies the arguments, which is your case, then the error is thrown.
Apart from that what #Kishan has suggested in terms of structure of code is correct. You need to differentiate between your tests and common functions.
#Test
public void assertBackToLogin(WebDriver driver) throws InterruptedException {
LoginPage login = new LoginPage (driver);
login.assertLogin();
}
Is NOT working
Remove all the parameters and run
#Test
public void assertBackToLogin() throws InterruptedException {
LoginPage login = new LoginPage (driver);
login.assertLogin();
}