How to replace static driver method - java

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();
}

Related

WebDriver cannot be initialized

I got NullPointerException when I run the #testCase
1. In FrameworkTestCases.class -> #BeforeClass I initialize the instance of the selected webdriver. The browser is running when I start the FrameworkTestCases.class as jUnit test, but when I reach the testCase it says NullPointerException. What is the reason? I also used a constructor with 2 arguments to inherit the driver from the Generic.class to LoginPageFactory.class, but nothing happened.
Here is my FrameworkTestCases class:
public class FrameworkTestCases {
static WebDriver driver;
private static String baseURl = "https://management.tacticlicks.com/";
static LoginPageFactory loginPage;
static Generic generic;
//WebDriver driver;
//static LoginPageFactory lpFactory;
#BeforeClass
public static void setUp() {
generic = new Generic(driver);
generic.getDriver(baseURl, "chrome");
}
#Test
public void test() {
System.out.println("Executing test");
loginPage
.fillUsernameField("ivailostefanov1989#gmail.com")
.fillPasswordField("astral8909")
.clickSubmit();
}
#AfterClass
public static void tearDown() {
driver.quit();
}
}
public class LoginPageFactory extends Generic {
public LoginPageFactory(WebDriver driver2, Class<LoginPageFactory> class1) {
super(driver2, class1);
// TODO Auto-generated constructor stub
}
WebDriver driver;
#FindBy(name="email") //.//*[#id='login']/div[1]/div/div/table/tbody/tr/td[2]/div[1]/form/div[1]/input
WebElement loginUsernameField;
#FindBy(name="password")
WebElement loginPasswordField;
#FindBy(tagName="button")
WebElement loginSubmitButton;
public LoginPageFactory(WebDriver driver) {
System.out.println("LoginPageFactory");
this.driver = driver;
PageFactory.initElements(driver, this);
}
public LoginPageFactory fillUsernameField(String username) {
System.out.println("Before field initializing");
WebElement emailField = driver.findElement(By.name("email"));
emailField.click();
emailField.sendKeys(username);
return this;
}
public LoginPageFactory fillPasswordField(String password) {
loginPasswordField.click();
loginPasswordField.clear();
loginPasswordField.sendKeys(password);
return this;
}
public LoginPageFactory clickSubmit() {
loginSubmitButton.click();
return this;
}
}
public class Generic {
WebDriver driver;
public Generic(WebDriver driver) {
this.driver = driver;
}
public Generic(WebDriver driver2, Class<LoginPageFactory> class1) {
// TODO Auto-generated constructor stub
}
private void getBrowser(String browser) {
if (browser.equalsIgnoreCase("Firefox")) {
File chromeDriver = new File("C:\\Users\\Ivo\\Desktop\\geckodriver.exe");
System.setProperty("webdriver.gecko.driver", chromeDriver.getAbsolutePath());
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("Chrome")) {
//set chromedriver property
File chromeDriver = new File("C:\\Users\\Ivo\\Desktop\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", chromeDriver.getAbsolutePath());
driver = new ChromeDriver();
} else {
System.out.println("Browser cannot be launched");
}
}
public WebDriver getDriver(String appUrl, String browser) {
getBrowser(browser);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get(appUrl);
return driver;
}
}
You are missing a variable assignment in #BeforeClass method.
Change
#BeforeClass
public static void setUp() {
generic = new Generic(driver);
generic.getDriver(baseURl, "chrome");
}
to
#BeforeClass
public static void setUp() {
generic = new Generic(driver);
driver = generic.getDriver(baseURl, "chrome");
}
And also you did not create any instance of LoginPageFactory class. You have created a variable static LoginPageFactory loginPage; but didn't initialize it (at least nowhere in provided code).
In method
#Test
public void test() {
System.out.println("Executing test");
//add this line of code to initialize elements via Page Factory
loginPage = new LoginPageFactory(driver);
loginPage
.fillUsernameField("ivailostefanov1989#gmail.com")
.fillPasswordField("astral8909")
.clickSubmit();
}

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 to call a method with two parameter one as xPath and other as sendkey value?

How can I solve this issue?
public class myClass {
WebDriver driver;
#Test
public void myTest() {
oasEnterValue("//input[#name='user']", "user1");
oasEnterValue("//input[#name='password']", "pwd1");
}
public void oasEnterValue(String fXPath, String fText) {
driver.findElement(By.xpath(fXPath)).sendKeys(fText);
}
}
I am getting NullpointerException at driver.findElement(By.xpath(fXPath)).sendKeys(fText);
Below is my full code:
public class myClass {
WebDriver driver;
#Test
public void myTest() {
browserGo("linkedin.com/");
oasEnterValue("//input[#name='user']", "user1");
oasEnterValue("//input[#name='password']", "pwd1");
}
public void oasEnterValue(String fXPath, String fText) {
driver.findElement(By.xpath(fXPath)).sendKeys(fText);
}
public void browserGo(String fURL) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(fURL);
}
From what I can tell, those XPaths don't exist. I think you want:
oasEnterValue("//*[#id='login-email']", "user1");
oasEnterValue("//*[#id='login-password']", "pwd1");

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.

How to reuse the exiting instance of webdriver for different classes

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

Categories

Resources