testNG problem runing a suite with open browser - java

I have 2 similar classes.
I changed the opening of the browser to ChromeOptions so the tests can't be execute when a browser is open.
When I am execute the testNG.xml (with the 2 tests) its open immiditly both of the browsers and the suite can't be run.
What should I need to change in order to execute this well ?
Thanks alot
public class Demo2 {
public static WebDriver driver;
public static void main(String[] args)
{
initializeDriver();
print2();
}
#BeforeTest
private static void initializeDriver() {
System.setProperty("webdriver.chrome.driver","C:\\Program Files\\Selenium\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/עמית/AppData/Local/Google/Chrome/User Data");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
#Test
public static void print2()
{
driver.get("https://www.google.com");
System.out.println("1");
driver.close();
}
}

I think this path C:/Users/עמית/AppData/Local/Google/Chrome/User Data") should use alphabet letters. Even if you try to use this, please config your font type to use the popular font as UTF-8.

Related

Java automation selenium convert to Pom or factory

I need help with creating Java automation with Selenium Webdriver to Pom or Pomm factory.
I've read how to create pom without any success.
Please help.
I need help on how to create java automation in pom. strong textHow to conver it?
String baseUrl = "https:amazon.com/";
WebDriver driver;
NavigationPom navigationPom;
private final boolean useFirefoxbrowser = false;
#BeforeClass
public static void setupClass() {
WebDriverManager.chromedriver().setup();
WebDriverManager.firefoxdriver().setup();
}
#Before
public void setUp() {
if (useFirefoxbrowser == false) {
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.addArguments("--width=1240", "--height=720");
driver = new FirefoxDriver(firefoxOptions);
} else {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--window-size=1920,1080");
driver = new ChromeDriver(chromeOptions);
}
}
#Test
public void MacbookTest1() {
driver.get(baseUrl);
driver.manage().window().maximize();
driver.findElement(By.xpath("//input[#id='twotabsearchtextbox']")).click();
driver.findElement(By.xpath("//input[#id='twotabsearchtextbox']")).sendKeys("macbook");
driver.findElement(By.xpath("//input[#id='nav-search-submit-button']")).click();
driver.findElement(By.xpath("//input[#id='nav-search-submit-button']")).click();
driver.findElement(By.xpath("//li[#id='p_89/Lenovo']/span/a/div/label/i")).click();
//Checkboxes
boolean enabled = driver.findElement(By.xpath("//li[#id='p_89/Lenovo']/span/a/div/label/i")).isEnabled();
Start from creating a simple implementation:
How the Page class might look:
class Page {
private WebDriver driver;
public Page(WebDriver driver) {
this.driver.driver = driver;
}
//Define locators
//Keep elements as By on the top of the class
private By someElement1 = By.xpath("...");
private By someElement2 = By.xpath("...");
//Define page methods
// Examples:
// public void clickSomeElement()
// public void fillSomeInput()
public void doSomeAction() {
WebElement element = driver.findElement(someElement1);
// do something with the element
// optionaly wait for something after action
}
// Examples:
// public boolean isPageLoaded()
// public boolean isSomeElementDisplayed()
// public String getSomeElementText()
// public int getSomeElementsCount()
public Object getSomeData() {
WebElement element = driver.findElement(someElement2);
// do something with the element and return
}
}
Use pages in your tests, do not work with WebDriver directly.
#Test
public void someTest() {
Page page = new Page(driver);
page.doStep1();
page.doStep2();
assertEquals(page.getSomeData(), "Some expected result", "Optional Error message");
}
And..
Start from creating a test scenario code, create test steps, which you like to have (methods, which will be underlined in IDE as non-existing), and think about the data, which you like to check.
Then just implement all the non-existing methods you need in Page classes.
Maybe it sounds complicated, but try to start from simple test scenarios and it should become more clear after some practice.
I had the same issue. If this is a Java project, with Eclipse and Intellij IDEA, you can right click the project and select Convert to Maven. From there, it's fine adjustments (versions) in the POM file.

Fail to run tests in Chrome headless mode

I am trying to run tests in Chrome headless mode but getting java.lang.NullPointerException
Chrome version: Version 72.0.3626.121 (Official Build) (64-bit)
Selenium version: 3.8.1
Chromedriver version: 2.45.615355
Here is my BaseTest:
public abstract class BaseTest {
public WebDriver driver;
protected abstract String getUrl();
#Before
public void setUp() {
Log.startLog("Test is Starting...");
System.setProperty("webdriver.chrome.driver", "src//test//resources//chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(true);
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get(getUrl());
}
#After
public void tearDown() {
Log.endLog("Test is Ending...");
driver.manage().deleteAllCookies();
driver.close();
}
}
When I'm running tests, not in headless mode every test works good but in headless mode, I can't even run a simple test to understand if the headless mode is working or not.
Test example:
#Test
public void test() {
System.out.println(driver.getTitle());
}
Example URL: https://www.wikipedia.org/
UPDATE:
I've created new sample project with this code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class test {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/Users/alexsomov/Desktop/chromedriver2");
//Set Chrome Headless mode as TRUE
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
//Instantiate Web Driver
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com/");
System.out.println("Page title is - " + driver.getTitle());
driver.close();
}
And bingo, everything works well... Need to figure out why code above from real project doesn't work seems something wrong with BaseTest class and when I run code with debugger I'm getting driver == null, maybe anyone have a solution how I can solve this problem :/
ANSWER
The solution was super easy, just need to change 1 string in setUp() method in BaseTest class.
This one:
WebDriver driver = new ChromeDriver(chromeOptions);
change to this:
driver = new ChromeDriver(chromeOptions);
and everything will work.
If you are using linux environment, may be you have to add --no-sandbox as well and also specific window size settings. --no-sandbox is no needed in windows if you set user container properly.
disable-gpu Only on Windows. Other platforms no longer require it. The --disable-gpu flag is a temporary work around for a few bugs.
if(browser.equalsIgnoreCase("HLChrome")){
//Headless chrome browser and configure
WebDriverManager.chromedriver().setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("disable-gpu");
// chromeOptions.addArguments("window-size=1400,2100"); // linux should be activate
driver = new ChromeDriver(chromeOptions);
ANSWER The solution was super easy, just need to change 1 string in setUp() method in BaseTest class.
This one:
WebDriver driver = new ChromeDriver(chromeOptions);
change to this:
driver = new ChromeDriver(chromeOptions);
and everything will work.

Open Chrome with selenium

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Users/myPC/Desktop/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
}
So I downloaded chromedriver.exe and tried opening Chrome using the following code, but every time I run this code I get the following error:
Error:java: package com.google.common.collect does not exist
And also whenever I try and run chromedriver.exe from desktop, chrome does not want to open.
Thanks in advance
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Users/myPC/Desktop/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("http://www.google.com");
}

Selenium Eclipse Test Suite tests fail in the suite, but are successful when run individually

I have the following test suite to run an automation script to login to gmail then another script to click the Compose button:
TestSuite.xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Web Admin Tests" parallel="false">
<test name="BOS - Account Class">
<classes>
<class name="secondtestngpackage.GmailComposeEmail" />
<class name="secondtestngpackage.GmailLogin" />
</classes>
</test>
</suite>
When I run this test suite, the first test does not get passed the login screen in gmail, but the second test does, even though they reference the same functions. Is there a reason why this would happen? One test is able to enter the user id and password, since it is the second/last test, but when the first test is run, it is like the second test interferes with it, since its browser is now in focus.
GmailLogin.java:
#BeforeTest
public void launchBrowser() {
ReuseFunctions.OpenApp("Chrome", "https://gmail.com");
}
//Test 1: Log into Gmail
#Test(priority=1)
public void LoginToGmailAccount() {
**GmailComposeEmail.java**
#BeforeTest
public void launchBrowser() {
ReuseFunctions.OpenApp("Chrome", "https://gmail.com");
}
#Test(priority=2)
public void LoginToGmailAccount() {
Reusable Functions File:
ReuseFunctions.func_EnterCredentials("username", "password");
public class ReuseFunctions {
public static WebDriver driver;
/*Function 1: Select Browser and Open Application Function
*/
public static Object OpenApp (String Browser, String URL) {
//Receive Browser Name Function
Func_LaunchBrowser(Browser);
//Receive Website and Open Function
func_OpenURL(URL);
return driver;
}
//Select Browser
public static WebDriver Func_LaunchBrowser(String Browser) {
String driverPath = "C:/EclipseJavaDev/";
if(Browser=="Chrome"){
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
driver = new ChromeDriver();
}else if(Browser=="FF"){
driver= new FirefoxDriver();
}else if(Browser=="IE"){
System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
driver= new InternetExplorerDriver();
}
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
return driver;
}
//Open URL
public static void func_OpenURL(String URL){
driver.get(URL);
driver.manage().window().maximize();
}
The problem lies with where your WebDriver instance is instantiated. Think of each instance of WebDriver as a unique browser session. So the safest way to ensure each test gets its own driver instance (browser session), is to initialize it at the Test class, not the common helper class.
GmailLogin:
// Initialize Webdriver and then asks your common function to return it
private WebDriver driver;
#BeforeTest
public void launchBrowser() {
driver = ReuseFunctions.OpenApp("Chrome", "https://gmail.com");
}
#Test(priority=1)
public void LoginToGmailAccount() {
// pass driver as a method argument to other methods
}
//Don't forget to close the browser
#AfterTest
public void quitBrowser() {
driver.quit();
}
Refactor your other Test class the same away as above. (Or reconsider if you really need another class. You could just add another method into the same class and use priority and/or dependsOnMethods attributes to control the execution order. But that is a different topic and out of the scope of this question :) ).
ReuseFunctions:
// Remove the global Webdriver instantiation
//Change return type from Object to WebDriver
public static WebDriver OpenApp (String Browser, String URL) {
WebDriver driver = Func_LaunchBrowser(Browser);
func_OpenURL(URL, driver); //pass in the driver as arg
return driver;
}
//Refactor openUrl method to use the driver from arg
public static void func_OpenURL(String URL, WebDriver driver){...}
This should work. Let me know how it goes.

Run Webdriver Junit browser specific test cases

I have selenium.properties in which i specify the test configuration (baseURL, browser etc). This is used by ant script to kick off webdriver junit test cases. Now I have few junit test methods, that i want to run only on Firefox. I was wondering if there a way i can accomplish this using JUnit annotations? can i create custom annotations?
my setup
public class TestBase{
public static String baseURL = null;
public static String browser = null;
#BeforeClass
public static void webdriverSetUp() {
try {
FileInputStream fn = new FileInputStream(SELENIUM_PROP_FILE);
Properties selenium_properties = new Properties();
selenium_properties.load(fn);
baseURL = selenium_properties.getProperty("baseUrl");
browser = selenium_properties.getProperty("browser");
} catch (Exception e) {
e.printStackTrace();
}
if(browserg.equalsIgnoreCase("firefox")){
File profileDirectory = new File("./profile");
FirefoxProfile profile = new FirefoxProfile(profileDirectory);
driver = new FirefoxDriver(profile);
}
}
//Test Class
public class TestCase1 extends TestBase{
#Test //run this case only if browser = firefox
public void test1(){
}
#Test //do not run this case if browser = chrome
public void test2(){
}
}
any pointers?
You can easily do this with JUnit with your own runner. In fact, there is a similar working code in Selenium WebDriver test - it's just backwards. The Selenium guys wanted to skip some tests for particular browsers, so they introduced a custom #Ignore annotation.
Take a look at JUnit4TestBase, SeleniumTestRunner and finally TestIgnorance.
You can use their idea to make the opposite and only run the tests with the desired drivers. However, I think you'll need to write it yourself as I am not aware of any good solution out there.

Categories