ExtentTest class throws null pointer error - selenium

Scope(This is what i want to do): Hey looking for to attached screenshot in my extent report file.
Problem: so now i have used the ExtentTest class in BaseClass file. but when i run my testsuit from testNG.xml file, it give me an below error.
java.lang.NullPointerException: Cannot invoke "org.testng.ITestResult.getStatus()" because "com.example.PageClass.BaseClass.result" is null
Here is my Code in BaseClass.
package com.example.PageClass;
import com.example.Utils.Utilities;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.ITestResult;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Duration;
import java.util.Properties;
public class BaseClass {
public static WebDriver driver;
public static Properties prop;
public static LoginPage loginPage;
public static ExtentTest extentTest;
public static ITestResult result;
public static void properties() {
try {
FileInputStream fis = new FileInputStream("src/main/resources/generic.properties");
prop = new Properties();
prop.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setDriver() {
properties();
if (prop.getProperty("browser").contains("chrome")) {
System.setProperty("webdriver.chrome.driver", prop.getProperty("driverPath"));
driver = new ChromeDriver();
} else {
// FirefoxDriverManager.firefoxdriver().setup();
// driver = new FirefoxDriver();
}
driver.get(prop.getProperty("url"));
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(60));
driver.manage().window().maximize();
loginPage = PageFactory.initElements(driver, LoginPage.class);
}
public static void closeDriver() throws IOException {
if (result.getStatus() == ITestResult.FAILURE) {
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getName()); //to add name in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getThrowable()); //to add error/exception in extent report
String screenshotPath = null;
try {
screenshotPath = Utilities.getUtilities().getScreenshot(driver, "firstScreenShot");
} catch (IOException e) {
throw new RuntimeException(e);
}
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath)); //to add screenshot in extent report
extentTest.log(LogStatus.PASS, extentTest.addScreenCapture(screenshotPath)); //to add screenshot in extent report
}
driver.quit();
}
}
code inside StepsDef file:
package com.example.StepDefinitions;
import com.example.PageClass.BaseClass;
import com.example.Utils.Utilities;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.*;
import java.io.IOException;
public class LoginStepDefs extends BaseClass implements ITestListener {
#Before
public void setup(){
setDriver();
}
#After
public void teardown() throws IOException {
closeDriver();
}
#Then("I go to OrangeHRM Home page.")
public void iGoToOrangeHomePage() {
try {
loginPage.getOrangeHRMHome();
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#When("I enter {string} username and {string} password.")
public void iEnterUsernameAndPassword(String arg0, String arg1) {
try {
loginPage.systemLogin(arg0,arg1);
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#When("I enter username and password.")
public void iEnterUsernameAndPassword() {
try {
loginPage.systemLogin("Admin","admin123");
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#And("I navigate to PIM tab and click on add employee.")
public void iNavigateToPIMTabAndClickOnAddEmployee() {
try {
loginPage.clickOnPIM().clickOnAddEmployee();
} catch (Exception e) {
System.out.println("Username not navigate to add employee tab.");
}
}
#And("I enter employee details and save it.")
public void iEnterEmployeeDetailsAndSaveIt() {
try {
loginPage.enterFirstNameAndLastName().fileUpload().checkBoxCreateLoginDetail().enterLoginDetail().verifySuccessMessage().verifySuccessMessageForAdd();
} catch (Exception e) {
System.out.println("Username not navigate to add employee tab.");
}
}
My Folder Structure:
Can Anyone please help me out in this?

Related

Unable to Configure Log4j2 using java.util.Properties

I am unable to configure log4j2 with java.util.properties. I always get this message "tatusLogger No Log4j 2 configuration file found". Please see my logger class. I am reading the log4j2 properties from two files.
I will be attaching my code to this post.
package my.common.logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
import org.apache.logging.log4j.util.PropertiesUtil;
public class MyLogger {
private static boolean configured = false;
private static Logger logger;
static {
System.setProperty("log4j.configurationFactory", "my.common.logger.JCFLog4JConfigurationFactory");
}
private static void readConfiguration() throws Exception {
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = ConfigurationFactory.getInstance().getConfiguration(context, createConfigurationSource());
configuration.start();
Configurator.reconfigure();
configured = true;
}
public static Logger getLogger(String className) {
try {
if (!configured) readConfiguration();
return org.apache.log4j.LogManager.getLogger(className);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static ConfigurationSource createConfigurationSource()
{ Properties p = new Properties();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = null;
try {
p.putAll(<Read from File 1>);
p.putAll(<Read from File 2>);
p.store(out, null);
} catch (IOException e) {
e.printStackTrace();
}
in = new ByteArrayInputStream(out.toByteArray());
ConfigurationSource configSrc = null;
try {
configSrc = new ConfigurationSource(in);
}
catch (IOException i)
{
i.printStackTrace();
}
return configSrc;
}
}
Here is Config Factory Code:
package nj.aoc.ito.cmfw.common.logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
public class MyLog4JConfigurationFactory extends ConfigurationFactory {
public MyLog4JConfigurationFactory() {
}
#Override
public Configuration getConfiguration(LoggerContext ctx, ConfigurationSource source) {
PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory();
return factory.getConfiguration(ctx, source);
}
#Override
protected String[] getSupportedTypes() {
return new String[]{".properties", "*"};
}
}
Any idea what I might be doing wrong?
Thanks
Nags

Getting NullPointerException when trying to access Selenium Webdriver instance in below scenario.

I am trying to create a framework where I can run my test cases(test tags in xml file) in parallel in different browsers. I have tried using all combinations of testNG annotations but after reading a blog came to know that this can only be achieved by using testNg listners. I am using ThreadLocal to keep my driver thread-safe. I am getting null pointer exception when trying to access Webdriver in my test cases class in line LocalDriverManager.getDriver().get(url);
This is LocalBrowserFactory.Class
package BrowserFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import DataProvider.ConfigDataProvider;
public class LocalDriverFactory {
public static WebDriver createInstance(String browserName) {
WebDriver driver = null;
ConfigDataProvider config=new ConfigDataProvider();
if (browserName.toLowerCase().contains("firefox")) {
System.setProperty("webdriver.gecko.driver", config.getgeckoPath());
driver = new FirefoxDriver();
}
if (browserName.toLowerCase().contains("internet")) {
driver = new InternetExplorerDriver();
}
if (browserName.toLowerCase().contains("chrome")) {
System.setProperty("webdriver.chrome.driver", config.getchromePath());
driver = new ChromeDriver();
}
driver.manage().window().maximize();
return driver;
}
}
This is my LocalDriverManager.class
package BrowserFactory;
import org.openqa.selenium.WebDriver;
public class LocalDriverManager {
private static ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return webDriver.get();
}
public static void setWebDriver(WebDriver driver) {
webDriver.set(driver);
}
}
This is my ConfigPropertyReader.class
package DataProvider;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class ConfigDataProvider {
static Properties p;
public ConfigDataProvider()
{
File f =new File("C:/Eclipse/parallelframework/configuration/config.properties");
try {
FileInputStream fis = new FileInputStream(f);
p=new Properties();
p.load(fis);
}
catch (Exception e)
{
System.out.println("Custom Exception- cannot load properties file"+e.getMessage());
}
}
public String getvalue(String key)
{
return p.getProperty(key);
}
public String getUrl()
{
return p.getProperty("url");
}
public String getchromePath()
{
return p.getProperty("chromepath");
}
public String getgeckoPath()
{
return p.getProperty("firefoxpath");
}
public String getIEPath()
{
return System.getProperty("User.dir")+p.getProperty("IEPath");
}
}
This is WebDriverListner.class
package Listners;
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
import BrowserFactory.LocalDriverFactory;
import BrowserFactory.LocalDriverManager;
public class WebDriverListner implements IInvokedMethodListener {
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
System.out.println(browserName);
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
System.out.println("Driver Set");
}
}
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
This is my sample testcase.class
package tests;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import BrowserFactory.LocalDriverManager;
public class sampleTest {
#Test
public void testMethod1() {
invokeBrowser("http://www.ndtv.com");
}
#Test
public void testMethod2() {
invokeBrowser("http://www.facebook.com");
}
private void invokeBrowser(String url) {
LocalDriverManager.getDriver().get(url);
}
}
Your Listener code is messed up. You basically have the beforeInvocation and afterInvocation in the wrong order.
Here's how it should have looked like
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
public class WebDriverListener implements IInvokedMethodListener {
#Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
}
}
#Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
You basically would setup the webdriver into the thread local variable (push the webdriver instance into the thread local variable's context) from within the beforeInvocation and then within your afterInvocation method, you would pop it out and clean up the webdriver instance (by calling quit() ). In your case, your code is doing the opposite.
For more details you can refer to my blog post here.

selenium webdriver giving "unknown error: Element is not clickable at point (747, 238)" when clicking on an angular js date picker

package redbus;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class Searchforbus {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.get("http://www.redbus.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.findElementById("src").sendKeys("Nagercoil");
driver.findElementByClassName("selected").click();
driver.findElementById("dest").sendKeys("Chennai");
driver.findElementByClassName("selected").click();
Thread.sleep(3000);
driver.findElementById("onward_cal").click();
WebElement element1= driver.findElementByXPath("//div[#id='rb-calendar_onward_cal']/table/tbody/tr[3]/td[6]");
System.out.println("Check1");
Actions builder= new Actions(driver);
builder.moveToElement(element1).click().perform();
System.out.println("Check2");
}
}
I am getting the below error:
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (747, 238). Other element would receive the click: <label for="onward_cal" style="font-family:Lato" class="db text-trans-uc move-up">...</label>
(Session info: chrome=54.0.2840.99)
at redbus.Searchforbus.main(Searchforbus.java:28)
#vinu the date you are provided in locator element1 points to 3rd December which is disabled in calender since it is past date, make sure you provide enabled/available dates
Make a habit of using explicit wait condition before clicking tricky element like calender
e.g WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("element_xpath")));
ref links
Rahul is right. You selected past date which is disabled. try to select future date and let us know what is the error if it fails.
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CommonSeleniumUtils extends Driver {
static WebDriver driver = Driver.getDriver();
public void switchToWindowByTitle(String title) {
Set<String> windows = driver.getWindowHandles();
System.out.println("Amount of windows that are currently present :: " + windows.size());
for (String window : windows) {
driver.switchTo().window(window);
if (driver.getTitle().startsWith(title) || driver.getTitle().equalsIgnoreCase(title)) {
break;
} else {
continue;
}
}
}
public void clickWithJS(WebElement elementtoclick) {
WebDriverWait wait = new WebDriverWait(driver, Long.parseLong(ConfigurationReader.getProperty("timeout")));
wait.until(ExpectedConditions.elementToBeClickable(elementtoclick));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", elementtoclick);
((JavascriptExecutor) driver).executeScript("arguments[0].click();", elementtoclick);
}
public void waitForPresenceOfElementByCss(String css) {
WebDriverWait wait = new WebDriverWait(driver, Long.parseLong(ConfigurationReader.getProperty("timeout")));
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(css)));
}
public void waitForVissibilityOfElement(WebElement element) {
WebDriverWait wait = new WebDriverWait(driver, Long.parseLong(ConfigurationReader.getProperty("timeout")));
wait.until(ExpectedConditions.visibilityOf(element));
}
public void waitForStaleElement(WebElement element) {
int i = 0;
while (i < 10) {
try {
element.isDisplayed();
break;
} catch (StaleElementReferenceException e) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
e.printStackTrace();
i++;
} catch (NoSuchElementException e) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
e.printStackTrace();
i++;
} catch (WebDriverException e) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
e.printStackTrace();
i++;
}
}
}
public boolean verifyElementIsNotPresent(String xpath) {
List<WebElement> elemetns = driver.findElements(By.xpath(xpath));
return elemetns.size() == 0;
}
public boolean verifyElementIsNotPresent(By by) {
List<WebElement> elemetns = driver.findElements(by);
return elemetns.size() == 0;
}
public void scrollToElement(WebElement element) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
public void hitEnterUsingRobot() {
Robot rb;
try {
rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public boolean verifyAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException Ex) {
System.out.println("Alert is not presenet");
}
return false;
}
public static void takeSnapShot() {
try {
TakesScreenshot scrShot = ((TakesScreenshot) driver);
File SrcFile = scrShot.getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir") + "\\screenshots.jpg";
System.out.println(path);
File DestFile = new File(path);
FileUtils.copyFile(SrcFile, DestFile);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void safeJavaScriptClick(WebElement element) throws Exception {
try {
if (element.isEnabled() && element.isDisplayed()) {
System.out.println("Clicking on element with using java script click");
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
} else {
System.out.println("Unable to click on element");
}
} catch (StaleElementReferenceException e) {
System.out.println("Element is not attached to the page document "+ e.getStackTrace());
} catch (NoSuchElementException e) {
System.out.println("Element was not found in DOM "+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to click on element "+ e.getStackTrace());
}
}
}
After this, call this method ===>>> safeJavaScriptClick
WebElement element = driver.findElement(By.xpath("YOUR XPATH"));
try {
seleniumTools.safeJavaScriptClick(element);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Selenium is unable to detect the Checkout button and add product in cart

The problem is, Selenium is unable to detect the Checkout button and add product in cart.
package automationFramework;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Checkout {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://sng.bestpricewebsitedesign.com/";
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
}
#Test
public void testNewCheckout() throws Exception {
driver.get(baseUrl + "/index.php?route=common/home");
driver.findElement(By.linkText("Home")).click();
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("input-email")).clear();
driver.findElement(By.id("input-email")).sendKeys("leo#abc.com");
driver.findElement(By.id("input-password")).clear();
driver.findElement(By.id("input-password")).sendKeys("asdfgh");
driver.findElement(By.cssSelector("input.btn.btn-primary")).click();
driver.findElement(By.linkText("Store")).click();
driver.findElement(By.xpath("(//button[#type='button'])[14]")).click();
driver.findElement(By.cssSelector("#cart > button.dropdown-toggle")).click();
driver.findElement(By.id("button-payment-address")).click();
driver.findElement(By.id("button-shipping-address")).click();
driver.findElement(By.id("button-shipping-method")).click();
driver.findElement(By.name("agree")).click();
driver.findElement(By.id("button-payment-method")).click();
driver.findElement(By.id("button-confirm")).click();
driver.findElement(By.linkText("Continue")).click();
driver.findElement(By.linkText("Logout")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
Following is the code for adding 'Blue Tshirt' in cart and perform check out.
#Test
public void testNewCheckout() throws Exception {
driver.get(baseUrl + "/index.php?route=common/home");
driver.findElement(By.linkText("Home")).click();
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("input-email")).clear();
driver.findElement(By.id("input-email")).sendKeys("leo#abc.com");
driver.findElement(By.id("input-password")).clear();
driver.findElement(By.id("input-password")).sendKeys("asdfgh");
//driver.findElement(By.cssSelector("input.btn.btn-primary")).click();
driver.findElement(By.xpath("//input[#value='Login']")).click();;
driver.findElement(By.linkText("Store")).click();
driver.findElement(By.xpath("//h4/a[text()='Blue Tshirt']/following::span[text()='Add to Cart'][1]")).click();
//driver.findElement(By.cssSelector("#cart > button.dropdown-toggle")).click();
driver.findElement(By.xpath("//div[#id='cart']/button[1]")).click();
driver.findElement(By.id("button-payment-address")).click();
driver.findElement(By.id("button-shipping-address")).click();
driver.findElement(By.id("button-shipping-method")).click();
driver.findElement(By.name("agree")).click();
driver.findElement(By.id("button-payment-method")).click();
driver.findElement(By.id("button-confirm")).click();
driver.findElement(By.linkText("Continue")).click();
driver.findElement(By.linkText("Logout")).click();
}
I have tested above code and it works fine for me. Please replace the existing test method with above one and let me know, if it works for you.

TestNG + Selenium woes. noClassDef error, TestNG based selenium test

I've followed a lot of the guides and forum posts online but haven't had any luck getting this to work inside TestNG. It's a selenium grid based test, programmed in eclipse.
Had trouble, so used the libraries listed in the suggestion of this forum post: http://clearspace.openqa.org/message/66867
I am trying to run the suite in the testNG test plugin for eclipse (org.testng.eclipse). Also tried running the jar from command line through selenium grid to no avail.
Since I'm not a java developer, to be honest I'm not entirely sure what to look for. I've some familiarity with Java thanks to the Processing environment, but I've kind of been thrown into java/eclipse for this task and am at a bit of a loss. Anyway, any help is appreciated and thank you in advance.
Here's my code:
suite.java:
package seleniumRC;
//import com.thoughtworks.selenium.*;
//import junit.framework.*;
//import java.util.regex.Pattern;
//import static org.testng.AssertJUnit.assertTrue;
//import org.testng.annotations.AfterMethod;
//import org.testng.annotations.BeforeMethod;
//import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class suite extends Testcase1 {
#Test(groups = {"example", "firefox", "default"}, description = "test1")
public void user1() throws Throwable {
testCase1();
}
#Test(groups = {"example", "firefox", "default"}, description = "test2")
public void user2() throws Throwable {
testCase1();
}
}
The actual test case
package seleniumRC;
//import com.thoughtworks.selenium.*;
//import org.testng.annotations.*;
//import static org.testng.Assert.*;
//import com.thoughtworks.selenium.grid.demo.*;
//import junit.framework.*;
//import com.ibm.icu.*;
//import java.util.regex.Pattern;
//import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
public class Testcase1 extends SeleneseTestNgHelper {
private static int $itter = 10;
public static void main(String args[]) {
//junit.textui.TestRunner.run(Suite());
}
//public static Test Suite() {
// return new TestSuite(Testcase1.class);
//}
// public void setUp() throws Exception {
// setUp("http://localhost:8080/test", "*firefox");
//}
#BeforeMethod(groups = {"default", "example"}, alwaysRun = true)
#Parameters({"seleniumHost", "seleniumPort", "browser", "webSite"})
protected void startSession(String seleniumHost, int seleniumPort, String browser, String webSite) throws Exception {
startSession(seleniumHost, seleniumPort, browser, webSite);
selenium.setTimeout("120000");
}
#AfterMethod(groups = {"default", "example"}, alwaysRun = true)
protected void closeSession() throws Exception {
closeSession();
}
public void testCase1() throws Exception {
selenium.open("/login.action#login");
selenium.type("userName", "foo");
selenium.type("password", "bar");
selenium.click("login");
selenium.waitForPageToLoad("30000");
selenium.click("link=test");
Thread.sleep(4000);
selenium.click("//tr[4]/td[1]/a");
if(selenium.isElementPresent("//input[#id='nextButton']") != false){
selenium.click("//div[2]/input");
}
Thread.sleep(2000);
for(int i=0; i < $itter; i++) {
if(selenium.isElementPresent("//label") != false){
selenium.click("//label");
selenium.click("submitButton");
Thread.sleep(1500);
}
else{ Thread.sleep(1500);}
}
selenium.click("//body/div[2]/div[1]/div/a");
Thread.sleep(1500);
selenium.click("//a[contains(text(),'Finish Now')]");
Thread.sleep(2000);
selenium.click("link=View Results");
Thread.sleep(30000);
selenium.click("showAllImgCaption");
Thread.sleep(12000);
selenium.click("generateTimeButton");
Thread.sleep(2000);
selenium.click("link=Logout");
selenium.waitForPageToLoad("15000");
}
}
and the SeleneseTestNGHelper class
package seleniumRC;
import java.lang.reflect.Method;
//import java.net.BindException;
import com.thoughtworks.selenium.*;
//import org.openqa.selenium.SeleniumTestEnvironment;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
//import org.openqa.selenium.environment.GlobalTestEnvironment;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
public class SeleneseTestNgHelper extends SeleneseTestCase
{
private static Selenium staticSelenium;
#BeforeTest
#Override
#Parameters({"selenium.url", "selenium.browser"})
public void setUp(#Optional String url, #Optional String browserString) throws Exception {
if (browserString == null) browserString = runtimeBrowserString();
WebDriver driver = null;
if (browserString.contains("firefox") || browserString.contains("chrome")) {
System.setProperty("webdriver.firefox.development", "true");
driver = new FirefoxDriver();
} else if (browserString.contains("ie") || browserString.contains("hta")) {
driver = new InternetExplorerDriver();
} else {
fail("Cannot determine which browser to load: " + browserString);
}
if (url == null)
url = "http://localhost:4444/selenium-server";
selenium = new WebDriverBackedSelenium(driver, url);
staticSelenium = selenium;
}
#BeforeClass
#Parameters({"selenium.restartSession"})
public void getSelenium(#Optional("false") boolean restartSession) {
selenium = staticSelenium;
if (restartSession) {
selenium.stop();
selenium.start();
}
}
#BeforeMethod
public void setTestContext(Method method) {
selenium.setContext(method.getDeclaringClass().getSimpleName() + "." + method.getName());
}
#AfterMethod
#Override
public void checkForVerificationErrors() {
super.checkForVerificationErrors();
}
#AfterMethod(alwaysRun=true)
public void selectDefaultWindow() {
if (selenium != null) selenium.selectWindow("null");
}
#AfterTest(alwaysRun=true)
#Override
public void tearDown() throws Exception {
// super.tearDown();
}
//#Override static method of super class (which assumes JUnit conventions)
public static void assertEquals(Object actual, Object expected) {
SeleneseTestBase.assertEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static void assertEquals(String actual, String expected) {
SeleneseTestBase.assertEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static void assertEquals(String actual, String[] expected) {
SeleneseTestBase.assertEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static void assertEquals(String[] actual, String[] expected) {
SeleneseTestBase.assertEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static boolean seleniumEquals(Object actual, Object expected) {
return SeleneseTestBase.seleniumEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static boolean seleniumEquals(String actual, String expected) {
return SeleneseTestBase.seleniumEquals(expected, actual);
}
#Override
public void verifyEquals(Object actual, Object expected) {
super.verifyEquals(expected, actual);
}
#Override
public void verifyEquals(String[] actual, String[] expected) {
super.verifyEquals(expected, actual);
}
}
So I solved this by dropping the seleniumTestNGHelper class and reworking the classpaths by way of the ant file. It required completely working my suite/original testcases, but worked well within Grid.