How to reuse the exiting instance of webdriver for different classes - java

I have gone through the existitng questions on this site, but unable to resolve
the following issue
Tools:Junit,IntelliJ,Java Language
//SetUp Class
public class SetUpTest {
public static WebDriver driver;
#BeforeClass
public static void setUpTest() throws InterruptedException
{
driver=new FirefoxDriver();
driver.get("http://www.ABC.co.uk");
Thread.sleep(5000);
}
//Test1
public class HomePageTest extends SetUpTest {
#Test
public void titleTest()
{
assertTrue(driver.getTitle().startsWith("ABC"));
//Test2
public void merchandisingTest() throws InterruptedException {
#Test
public void merchandisingTest()
{
driver.navigate().to("http://ABC.co.uk/deals");
assertThat(driver.getPageSource(),containsString("deals"));
I have tried running the tests with #TestBefore but still two browser windows are opened
one for Test1 and the other for Test2.I have also used #Suite.SuiteClasses
but the problem is still there.

Can you try this code
public class BaseTest{
public WebDriver driver;
#BeforeSuite
public void startDriver(){
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(5l, TimeUnit.SECONDS);
driver.get("http://www.ABC.co.uk");
}
}
public class HomePageTest extends BaseTest{
#Test
public void titleTest(){
assetTrue(driver.getTitle().startsWith("ABC"));
}
#Test
public void merchanisingTest(){
driver.navigate().to("http://www.ABC.co.uk/deals");
assertTrue(driver.getTitle().startsWith("deals"));
}
}
Also, you are running this using TestNG XML I guess, within which the #BeforeSuite method is called only once

Related

How to replace static driver method

public class CommonFunctions {
public static WebDriver driver;
public void openWebsite(String url) {
driver.get(url);
}
public void closeBrowser() {
driver.close();
}
}
public class TestCase {
CommonFunctions commonFunctions = new CommonFunctions();
#BeforeMethod
public void openWeb() {
homePage.openWeb();
}
#Test
public void navigateLoginPage() {
homePage.login();
}
#AfterMethod
public void closeBrowser() {
commonFunctions.closeBrowser();
}
}
I have two class (commonfunction,homepage and testcase). When I run code without "static" at "public static Webdriver driver", the code throw nullpointerexception at function "closeBrowser". How to fix this error. I don't want use method "public static Webdriver driver" as code.
You need to initialize your driver variable in your CommonFunctions class.
WebDriver driver = new WebDriver(... etc);
Or, write a constructor that initializes this variable.
public class CommonFunctions
{
public WebDriver driver;
public CommonFunctions() // Constructor
{
driver = new WebDriver();
}

java.lang.NullPointerException error witt #Test [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I am new to this java Selenium.
I have 2 classes. 1 parent and 1 child.
I have some methods in the parent class.
I pass 2 of them to the child class.
The problem is only 1 method (from the parent) executes and the 2nd failed.
can you help me to understand why I am getting the error and how to resolve it please :
"java.lang.NullPointerException"
Parent class :
public class SignUp {
public WebDriver driver;
public void go(WebDriver driver)
{
driver.findElement(By.id("id_sign_up")).click();
}
#Test
public void signup(WebDriver driver)
{
driver.findElement(By.linkText("I’m an advertiser")).click();
}
public void FormSign (WebDriver driver)
{
driver.findElement(By.xpath("//span[#css='1']")).sendKeys("Miron");
}
}
Child class :
public class OpenBrowser extends SignUp{
#Test
public void Start() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://account.admitad.com/en/sign_in/");
SignUp sg = new SignUp();
sg.go(driver);
//sg.signup(driver);
}
#Test
public void miron ()
{
SignUp mi = new SignUp();
mi.signup(driver);
}
Can someone please help me?
Thanks in advance
Ans: WebDriver driver object is inside Start().
Object declaration should be defined out side. Then all methods can access driver obj.
public class SignUp {
public WebDriver driver;
public void go(WebDriver driver)
{
driver.findElement(By.id("id_sign_up")).click();
}
//#Test
public void signup(WebDriver driver)
{
driver.findElement(By.linkText("I’m an advertiser")).click();
}
public void FormSign (WebDriver driver)
{
driver.findElement(By.xpath("//span[#css='1']")).sendKeys("Miron");
}
}
/*******************/
public class OpenBrowser extends SignUp{
WebDriver driver = null;
#BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://account.admitad.com/en/sign_in/");
}
#Test
public void Start() throws InterruptedException
{
SignUp sg = new SignUp();
sg.go(driver);
//sg.signup(driver);
}
#Test
public void miron ()
{
SignUp mi = new SignUp();
mi.signup(driver);
}
}

Error While creating PageObject Module in selenium For simple Tesng Testcase

I tried to Create a Simple Program in Selenium Using PageObjectModel. While Running the Program it throws Null Pointer Exception. Don't Know what i am doing wrong.Is my initialization of Variable is Wrong. I know i am making mistake in initializing the By locator but don't know what i am doing wrong.
public class main extends Base{
private static final int TIMEOUT = 5;
private static final int POLLING = 100;
protected WebDriverWait wait;
protected static WebElement ele;
protected By locator;
public void Base() {
wait = new WebDriverWait(driver, TIMEOUT, POLLING);
}
public WebElement waitForElementToAppear(By locator) {
wait.until(ExpectedConditions.presenceOfElementLocated(locator));//Line which Throws Null
return ele;
}
protected void waitForElementToDisappear(By locator) {
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
}
protected void waitForTextToDisappear(By locator, String text) {
wait.until(ExpectedConditions.not(ExpectedConditions.textToBe(locator, text)));
}
#Test()
public void getURL() {
driver.get("https://www.google.com");
waitForElementToAppear(By.name("q")).sendKeys("Pom");// Line Which Throws Null.
}
And My Base Class Code where i have saved the properties of the driver.
public class Base {
protected WebDriver driver;
public WebDriver getDriver() {
return driver;
}
public void setDriver(WebDriver driver) {
this.driver = driver;
}
#BeforeSuite
public void beforeSuite() {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver.exe"); // You can set this property elsewhere
driver=new ChromeDriver();
driver.manage().window().maximize();
}
}
The problem lies in the way in which you are initialising the WebDriverWait object.
Your WebDriver object will get instantiated only when the #BeforeSuite method runs in your Base class.
The logic of initialising the WebDriverWait is part of the method public void Base() in your main class.
But your #Test annotated getURL() method does not invoke Base() method. So your wait object is always null.
To fix this, invoke Base() within your #Test method or have your Base() method annotated with #BeforeClass annotation, so that it gets automatically called by TestNG.
There are multiple problems in your code
Probably you do not need global variable declarations. Of course you can do it like that but make sure you initialize them.
Do not put test methods in your page object
ele will always be null
Call the constructor
Probably you need something like following:
public class MyPageObject extends Base{
private static final int TIMEOUT = 5;
private static final int POLLING = 100;
protected WebDriverWait wait;
public void MyPageObject() {
super(); //Call constructor of Base if needed
wait = new WebDriverWait(driver, TIMEOUT, POLLING); //init wait
}
public WebElement waitForElementToAppear(By locator) {
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
return driver.findElement(locator); //return WebElement
}
protected void waitForElementToDisappear(By locator) {
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
}
protected void waitForTextToDisappear(By locator, String text) {
wait.until(ExpectedConditions.not(ExpectedConditions.textToBe(locator, text)));
}
}
public class MyTestClass {
#Test()
public void getURL() {
MyPageObject myPageObject = new MyPageObject(); //Initialize your page object
driver.get("https://www.google.com");
myPageObject.waitForElementToAppear(By.name("q")).sendKeys("Pom");
}

Selenium Java base class for all browser drivers and code which is redundant

I am new in Selenium and Java and I need help with base class. I have I base where I set methods for driver browsers and for its close. Problem is that when I call these method from main always web driver is called and browser is open many times. What is best practice if I don't want to have code duplication
and I want a good structure of project.
Main:
public class Main extends TestBase {
public static void main(String[] args) throws InterruptedException, ClassNotFoundException, SQLException {
LoginTest LoginTest = new LoginTest();
LogofTest LogofTest = new LogofTest();
TestBase TestBase = new TestBase();
LoginTest.setUpBeforeTestMethod();
LoginTest.loginAsAdmin();
LogofTest.logofAsAdmin();
LoginTest.tearDownAfterTestClass();
}
}
TestBase:
public class TestBase {
String a = System.setProperty("webdriver.chrome.driver",
"path");
WebDriver driver = new ChromeDriver();
protected WebDriver setUpBeforeTestClass() {
return driver;
}
protected void setUpBeforeTestMethod() {
driver.get("website");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void tearDownAfterTestClass() {
driver.close();
}}
LoginTest:
public class LoginTest extends TestBase {
public void login() throws InterruptedException {
WebElement username = driver.findElement(By.name("username"));
username.sendKeys("username");
}
}
The main focus is that I don't want to write again
WebDriver driver = new ChromeDriver();
driver.get("website"); System.setProperty("webdriver.chrome,"path");
for each test in function or class. So I want to create base class and inherit from it.
Example Selenium Test with JUnit using the Page Object Model
TestBase
public class TestBase
{
private String a = System.setProperty("webdriver.chrome.driver", "path");
protected WebDriver driver;
#Before //Before each test case, use BeforeClass for before each test class
public static void setUpBeforeTestCase() {
driver = new ChromeDriver();
driver.get("website");
}
#After
public static void tearDownAfterTestCase() {
driver.Quit(); //driver.Close() closes the window, but doesn't properly dispose of the driver
}
}
LoginTest:
public class LoginTest extends TestBase {
#Test
public void loginAndOutAsAdmin(){
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
LandingPage landingPage = loginPage.login("adminUser", "adminPassword");
landingPage.logout();
//Do some sort of assert here that you are logged out
}
}
BasePage
public class BasePage
{
protected WebDriver driver;
//Other common stuff your Page Objects will do, like wait for an element
}
LoginPage
public class LoginPage extends BasePage
{
#FindBy(how = How.NAME, using = "username")
private WebElement usernameBox;
//something for passwordBox and loginButton
public LoginPage(WebDriver currentDriver)
{
driver = currentDriver;
}
public LandingPage login(String username, String password)
{
usernameBox.sendKeys(username);
passwordBox.sendKeys(password);
loginButton.click();
return PageFactory.initElements(driver, LandingPage.class);
}
}
I haven't tried to compile this, but that's the basic idea. I'll let you fill in the details.

How make webdriver not to close browser window after each test?

I'm new in both Selenium WebDriver and Java. I have some webservices on my site on page /someservice.php. I've wrote few tests on Selenuim and they work fine. Code example (Main Class):
public class SiteClass {
static WebDriver driver;
private static boolean findElements(String xpath,int timeOut ) {
public static void open(String url){
//Here we initialize the firefox webdriver
driver=new FirefoxDriver();
driver.get(url);
}
public static void close(){
driver.close();
}
WebDriverWait wait = new WebDriverWait( driver, timeOut );
try {
if( wait.until( ExpectedConditions.visibilityOfElementLocated( By.xpath( xpath ) ) ) != null ) {
return true;
} else {
return false;
}
} catch( TimeoutException e ) {
return false;
}}
public static Boolean CheckDiameter(String search,String result){
driver.findElement(By.xpath("//input[#id='search_diam']")).sendKeys(search);
WebDriverWait wait = new WebDriverWait(driver, 5);
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[#class='ac_results'][last()]/ul/li")));
WebElement searchVariant=driver.findElement(By.xpath("//div[#class='ac_results'][last()]/ul/li"));
Actions action = new Actions(driver);
action.moveToElement(searchVariant).perform();
driver.findElement(By.xpath("//li[#class='ac_over']")).click();
Boolean iselementpresent = findElements(result,5);
return iselementpresent;
}
}
Code Example (Test Class)
#RunWith(Parameterized.class)
public class DiamTest {#Parameters
public static Collection<Object[]> diams() {
return Arrays.asList(new Object[][] {
{ "111", "//div[#class='jGrowl-message']",true},
{ "222", "//div[#class='jGrowl-message']",false},
{ "333", "//div[#class='jGrowl-message']",true},
});
}
private String inputMark;
private String expectedResult;
private Boolean assertResult;
public DiamTest(String mark, String result, boolean aResult) {
inputMark=mark;
expectedResult=result;
assertResult=aResult;
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
/**
* Test of CheckDiameter method, of class CableRu.
*/
#Test
public void testCheckDiameter() {
SiteClass obj=new SiteClass();
obj.open("http://example.com/services.php");
assertEquals(assertResult, obj.CheckDiameter(inputMark, expectedResult));
obj.close();
}
}
Now I have 2 tests like that with 3 parameters each (total 6 variants). As you can see in every variant I create new browser window and when I run all 6 variants that take too much time (up to 80 seconds).
How can I run all variants in one browser window to speed up my tests?
Just move contents of public static void close() method from your SiteClass to tearDownClass() method in DiamTest class. In this way the browser window will be closed when the class execution finished (because of #AfterClass annotation). Your code then should look like this:
//DiamTest class
#AfterClass
public static void tearDownClass() {
driver.close();
}
It's also a good practice to move browser window initialization to setUpClass() method which will be executed before each test class (according to #BeforeClass annotation)
//DiamTest class
#BeforeClass
public static void setUpClass() {
//Here we initialize the firefox webdriver
driver=new FirefoxDriver();
driver.get(url);
}
What you need to do is share your help class with all your tests, this mean, you should create an instance of SiteClass inside your setUpClass method.
This method are annotated with #BeforeClass assuring your test class will create this method will be executed before all the test be executed.
You can read more about #BeforeClass in jUnit doc: or have a simple overview in this response.
You will also need do some rewrite some code to allow share the driver with the another test, something like this:
#RunWith(Parameterized.class)
public class DiamTest {
#Parameters
public static Collection<Object[]> diams() {
return Arrays.asList(new Object[][] {
{ "111", "//div[#class='jGrowl-message']",true},
{ "222", "//div[#class='jGrowl-message']",false},
{ "333", "//div[#class='jGrowl-message']",true},
});
}
private String inputMark;
private String expectedResult;
private Boolean assertResult;
private static SiteUtil siteUtil;
public DiamTest(String mark, String result, boolean aResult) {
inputMark=mark;
expectedResult=result;
assertResult=aResult;
}
#BeforeClass
public static void setUpClass() {
siteUtil = new SiteUtil();
}
#AfterClass
public static void tearDownClass() {
siteUtil.close();
}
#Test
public void testCheckDiameter() {
siteUtil.open("http://example.com/services.php");
assertEquals(assertResult, obj.CheckDiameter(inputMark, expectedResult));
}
}
and:
public class SiteClass {
static WebDriver driver;
public SiteClass() {
driver = new FirefoxDriver();
}
public void open(String url){
driver.get(url);
}
...
Tip:
You should read about the TestPyramid.
Since functional tests are expensive, you should care about what is really necessary test. This article is about this.

Categories

Resources