Code trials:
#BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:/Users/hp/Downloads/chromedriver_win32/chromedriver.exe");
driver = new ChromeDriver();
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://www.google.com");
}
#Test
public void verifyTitle() {
System.out.println("demo");
String title =driver.getTitle();
System.out.println("the page title is :"+title);
Assert.assertEquals(title,"Google");
}
#AfterMethod
public void tearDown() {
driver.quit();
}
This is the code I am trying to run using Selenium Testng but showing error as Test case not found
As you are using TestNG you need to add the following import:
import org.testng.annotations.Test;
Related
I'm working on a Java Project using Selenium. I have attempted to implement my test codes. Below here is the snippet of it.
AutoTest
public class AutoTest {
WebDriver driver = null;
#BeforeTest
public void setUp() {
String projectPath = System.getProperty("user.dir");
DesiredCapabilities handlSSLErr = DesiredCapabilities.chrome ();
handlSSLErr.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true);
//Configuration for WebDriver
System.setProperty("webdriver.chrome.driver", projectPath+"/drivers/chromedriver/chromedriver.exe");
driver = new ChromeDriver(handlSSLErr);
}
#Test
public void createTopUpRequest() {
//browse to UAT Server
driver.get("https://10.2.5.215:33000/viewTopUpRequest");
//enter credentials
LoginPage.usernameLogin(driver).sendKeys("ezltest2svc");
LoginPage.passwordLogin(driver).sendKeys("Password123!");
//Click on submit button
LoginPage.loginButton(driver).sendKeys(Keys.RETURN);
}
#AfterTest
public void closeBrowser() {
//driver.close();
}
}
As soon as it tries navigating to this portal: "https://10.2.5.215:33000/viewTopUpRequest", I get the NET::ERR_CERT_COMMON_NAME_INVALID exception. May I know how to bypass the security protocols?
I'm not sure if org.openqa.selenium.remote.DesiredCapabilities even provides such option.
I'm using org.openqa.selenium.chrome.ChromeOptions:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public static String userDir = System.getProperty("user.dir");
public static String chromedriverPath = userDir + "\\resources\\chromedriver.exe";
public static WebDriver startChromeDriver() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
return driver;
}
This works as well:
public static WebDriver startChromeDriver() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.setAcceptInsecureCerts(true);
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
return driver;
}
Tested on https://badssl.com/
I'm a beginner Selenium practitioner. I have 2 classes, one for the WebDriver another is for Log In. I followed some youtube tutorials but can't pinpoint what I'm doing wrong. I tried the concept of 'Baseclass' where I extend the other class.
LogIn Class
WebDriver Class
If I add the WebDriver in the other class, it will run successfully. But I want to make it more 'organized'
this is the error
Error message
public Webdriver driver;
Please add static in this line
public static Webdriver driver;
because you need use same driver instance for all classes
create above line in top of both classes
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
public class TestApp {
private WebDriver driver;
private static TestApp myObj;
// public static WebDriver driver;
utils.PropertyFileReader property = new PropertyFileReader();
public static TestApp getInstance() {
if (myObj == null) {
myObj = new TestApp();
return myObj;
} else {
return myObj;
}
}
//get the selenium driver
public WebDriver getDriver()
{
return driver;
}
//when selenium opens the browsers it will automatically set the web driver
private void setDriver(WebDriver driver) {
this.driver = driver;
}
public static void setMyObj(TestApp myObj) {
TestApp.myObj = myObj;
}
public void openBrowser() {
//String chromeDriverPath = property.getProperty("config", "chrome.driver.path");
//String chromeDriverPath = property.getProperty("config", getChromeDriverFilePath());
System.setProperty("webdriver.chrome.driver", getChromeDriverFilePath());
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void navigateToURL() {
String url =property.getProperty("config","url");
;
driver.get(url);
}
public void closeBrowser()
{
driver.quit();
}
public WebElement waitForElement(By locator, int timeout)
{
WebElement element = new WebDriverWait(TestApp.getInstance().getDriver(), timeout).until
(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
private String getChromeDriverFilePath()
{
// checking resources file for chrome driver in side main resources
URL res = getClass().getClassLoader().getResource("chromedriver.exe");
File file = null;
try {
file = Paths.get(res.toURI()).toFile();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
}
//create package name called utils and under that package create class name with TestApp and paste above code
if you want use driver anywhere in your project
TestApp.getInstance().getdriver();
You didn't initialize your driver anywhere.
You need to use a before
#BeforeClass
public void setupClass(){
driver = new Chromedriver();
}
and in opensite
public static WebDriver driver;
You want your OpenSite class to act as the base class which you can extend it to your test class to intialize your driver. Remove your "#test" annotaion from the OpenSite class.
Add static with "public WebDriver driver";
Create a method openBrowser(already there) or driverInitialization in this class.
Return the driver instance.
Updated code will look like
public class OpenSite{
public static WebDriver driver;
public static void openBrowser(){
System.setProperty("webdriver","path");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("your URL");
return driver;
}
}
And in test class LogIn extend this class and call this method:
public class LogIn extends OpenSite{
#BeforeTest
public void driver initialization(){
openBrowser();
}
#Test
public void logInVendor(){
//Write your code here
}
}
I have a Java Automation script. I have a set up method that works but my tearDown isn't being read for some reason.
When I run my Automation test I seem to have two problems
If it fails the test run multiple times and the browser window stays open.
even if a test passed the browser window never closes, which makes things really messy.
I haven't added any feature files of code for the actual test as I think the issue is in the set up but more than happy to.
I suspect both issues are linked but I can't fathom where or how.
Here is my SeleniumSetUp Class
public class SeleniumSetup {
protected WebDriver driver;
public SeleniumSetup(WebDriver driver)
{
}
public SeleniumSetup() {
}
public void prepareBrowserForSelenium() {
// setup();
if(DriverSingleton.getDriver() == null)
{
setup();
}
else
{
driver = DriverSingleton.getDriver();
}
}
public void setup() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Selenium and drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://the-internet.herokuapp.com/");
driver.manage().window().maximize();
System.out.println("Set up running");
}
public void tearDown() {
driver.quit();
System.out.println("Tear down running");
}
}
I have added a Println and can see that this is never returned when I run my script.
Here's my Base Page;
package pages;
import org.openqa.selenium.WebDriver;
public class BasePage {
protected WebDriver driver;
public BasePage(WebDriver driver) {
this.driver = driver;
}
}
And my Driver
package support;
import org.openqa.selenium.WebDriver;
public class DriverSingleton {
private static WebDriver driver;
public DriverSingleton () {
}
public static WebDriver getDriver() {
return driver;
}
public static void setDriver (WebDriver driver) {
DriverSingleton.driver = driver;
}
}
Any help would be most appreciated.
It seems your DriverSingleton's driver never been initialized, and in setup() method of SeleniumSetup class, driver of SeleniumSetup is initialized and used every time you run the code , put the tearDown() at the end of setup() and your browser window will close.
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Selenium and drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://the-internet.herokuapp.com/");
driver.manage().window().maximize();
System.out.println("Set up running");
// <<------your test scenario should be placed here
tearDown();
Try extending your driver class with junit(j5 jupiter) interfaces and override the before/after methods, here is a simple example, using some of your code:
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
public class Driver implements AfterTestExecutionCallback, BeforeTestExecutionCallback, BeforeAllCallback, AfterAllCallback {
protected WebDriver driver;
#Override
public void beforeAll(ExtensionContext context) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Selenium and drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://the-internet.herokuapp.com/");
driver.manage().window().maximize();
System.out.println("Set up running");
}
#Override
public void afterAll(ExtensionContext context) throws Exception {
driver().quit();
}
#Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
//whatever steps you need before EACH test, like navigate to homepage etc...
}
#Override
public void afterTestExecution(ExtensionContext context) throws Exception {
// steps do to after each test, best practice is to clear everything:
driver.manage().deleteAllCookies();
driver.executeScript("window.sessionStorage.clear()");
driver.executeScript("window.localStorage.clear()");
}
}
I am having an issue with this class where I am receiving a null pointer exception. I inserted System.out.println("driver=" + driver); to see what is outputted and it states the driver=null for each dataset which makes me think there is a problem with the initialization when I hit the method under #Test. How can I resolve this initialization of the driver to get my tests to pass in testNG?
Below is the code:
package com.testng.practice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class LoginTest {
WebDriver driver = null;
#BeforeTest
public void invokeApplication() {
System.setProperty("webdriver.chrome.driver", "xxx\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
}
#Test (dataProvider = "getData")
public void loginFaceBook(String email, String password) {
System.out.println("driver=" + driver);
WebElement emailField = driver.findElement(By.name("email"));
WebElement passwordField = driver.findElement(By.name("pass"));
emailField.sendKeys(email);
passwordField.sendKeys(password);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#DataProvider
public Object[][] getData(){
//declared object of 4 rows and 2 columns
Object[][] dataSet = new Object[4][2];
dataSet[0][0] = "TimSmith#gmail.com";
dataSet[0][1] = "Smith123";
dataSet[1][0] = "JaneMcCormack#gmail.com";
dataSet[1][1] = "McCormack123";
dataSet[2][0] = "AnjaliPrakash#gmail.com";
dataSet[2][1] = "Prakash123";
dataSet[3][0] = "JamesBean#gmail.com";
dataSet[3][1] = "Bean123";
return dataSet;
}
}
This definition of the driver variable is valid within the invokeApplication() method and leaves the class attribute driver uninitialized
WebDriver driver = new ChromeDriver();
to initialize the class attribute use:
this.driver = new ChromeDriver();
I think the problem should be in the #BeforeTest annotation if you are running the class it self by running as TestNG.
BeforeTest annotation is working before the tag in the xml runner file.
Here is the definition of BeforeTest from TestNG documentation.
#BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
If you want to run before #Test you need to use #BeforeMethod.
Please pay attentionto the differences between all the annotation.
You can find differences here.
you declare WebDriver driver=null; Globally.
Then No Need To Declare once in Method invokeApplication();
write only
WebDriver driver = null;
#BeforeTest
public void invokeApplication() {
System.setProperty("webdriver.chrome.driver", "xxx\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
Can anyone help me with AssertEquals?
I have the below code for my test case class, but after AssertEquals fails, the test continues to proceed to the next method i.e. createClientTodelete. Why?
public class Client
{
public String baseUrl = "http://test.abc.com";
public WebDriver driver;
#BeforeTest
public void setBaseURL()
{
driver = new FirefoxDriver();
driver.get(baseUrl);
driver.manage().window().maximize();
}
#Test(priority = 0, description = "verify successful login")
public void verifyLogin()
{
String expectedDashTitle = "oms";
String actualDashTitle = driver.getTitle();
Assert.assertTrue(driver.findElements(By.name("username")).size()>0);
Assert.assertTrue(driver.findElements(By.name("password")).size()>0);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("123#123");
driver.findElement(By.name("login")).submit();
Assert.assertEquals(actualDashTitle, expectedDashTitle,"Title Not Found!");
}
#Test(priority = 1, description = "verify client is created successfully")
public void createClientTodelete()
{
driver.findElement(By.xpath(".//*[#id='mainMenu']/ul/li[2]/a/span")).click();
Assert.assertTrue(driver.findElements(By.linkText("Create")).size()>0);
driver.findElement(By.linkText("Create")).click();
driver.findElement(By.id("company_name")).sendKeys("TestCompany");
driver.findElement(By.id("contact_person_firstname")).sendKeys("FirstName");
driver.findElement(By.id("contact_person_lastname")).sendKeys("LastName");
driver.findElement(By.id("contact_person_email")).sendKeys("abc#test.com");
driver.findElement(By.id("save")).click();
}
By looking at your code, its clear that you are using TestNG for these test.
In TestNG, you can use "dependsOnMethods" property as below.
package sample.testng;
import org.testng.annotations.Test;
import org.testng.Assert;
public class SampleTest {
#Test
public void test(){
System.out.println("Executing test 1");
Assert.assertEquals("ABCD", "abc");
}
#Test(dependsOnMethods={"test"})
public void test1(){
System.out.println("Second test runs only if the first one is successful, otherwise its ignored");
//Asserts or whatever
}
}