While doing testing i got error as one of test ignored and second failed. have posted both classes of test class and driver manger and also error showing after executing test.
This is my test class:
#BeforeSuite
public void setUp(){
driver = DriverManager.getWebDriver();
driver.get(Configuration.getInstance().getProperty("appUrl"));
}
#Test
public void testrequestDemo(){
topNavigation = new TopNavigation(driver);
page = topNavigation.clickRequestDemoLink();
page.KeyInEmail("Azhar#gmail.com")
.and().KeyinCompany("ABC");
}
DriverManager Class :
public class DriverManager {
private WebDriver driver;
private static DriverManager manager;
private DriverManager(){
init();
driver = createDriver();
}
private void init(){
System.setProperty("webdriver.chrome.driver",
Configuration.getInstance().getProperty("chrome.executable"));
}
/**
* This method will create webdriver instance based on the
* property provided.
* #return
*/
private WebDriver createDriver(){
if(Configuration.getInstance().getProperty("browser").equals(Constants.CHROME)){
return new ChromeDriver();
}
else if(Configuration.getInstance().getProperty("browser").equals(Constants.FIREFOX)){
return new FirefoxDriver();
}else {
return new ChromeDriver();
}
}
private WebDriver getDriver() {
return driver;
}
public static WebDriver getWebDriver(){
if(manager==null){
manager = new DriverManager();
return manager.getDriver();
}
return manager.getDriver();
}
}
This is error I am getting
For setUP test fail
For testrequestDemo test ignored>
co.pragra.testingframework.drivermanager.DriverManager.createDriver(DriverManager.java:99)
co.pragra.testingframework.drivermanager.DriverManager.(DriverManager.java:73)
co.pragra.testingframework.drivermanager.DriverManager.getWebDriver(DriverManager.java:113)
co.pragra.testingframework.testcases.HomePageTest.setUp(HomePageTest.java:37)
Related
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();
}
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");
}
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();
}
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.
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.