I am new to TestNG Selenium Webdriver,
I want to separate Tests in different classes how to do that, and I am not able to understand the parameters to pass against each tests from the actual.
Here is my code
package Examples;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class Flipkart {
public static WebDriver driver;
#BeforeClass
public void beforeClass()
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30000, TimeUnit.MILLISECONDS);
}
#Test
public void FlipkartTest() throws InterruptedException
{
driver.get("https://www.flipkart.com/");
driver.manage().window().maximize();
navback();
ArrayList<String> arrayList1 = new ArrayList<String>();
arrayList1.add("Samsung");
arrayList1.add("Nokia");
arrayList1.add("Micromax");
arrayList1.add("Sony");
arrayList1.add("Brands");
arrayList1.add("Android");
arrayList1.add("Windows");
for(int i=0; i<arrayList1.size(); i++)
{
String xpath = "//*[contains(#href,'%s')]";
String y = arrayList1.get(i);
String xpathOfElement = String.format(xpath, String.valueOf(y));
System.out.println("Name 1 "+driver.findElement(By.xpath(xpathOfElement)).getText());
driver.findElement(By.xpath(xpathOfElement)).click();
System.out.println("Count 1: "+driver.findElement(By.xpath("//*[#id='searchCount']")).getText());
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("price_range");
arrayList.add("type");
arrayList.add("screen_size");
arrayList.add("features");
arrayList.add("primary_camera");
for(int j=0; j<arrayList.size(); j++)
{
String x = arrayList.get(j);
WebElement ul = driver.findElement(By.id(x));
List<WebElement> lis = ul.findElements(By.tagName("li"));
for (WebElement li : lis)
{
System.out.print(" 1st part: "+li.getAttribute("title")); //To get "Rs. 2001 - Rs. 5000"
System.out.println(" 2nd part: "+li.findElement(By.xpath(".//span[#class='count']")).getText());
}
System.out.println("");
}
navback();
}
}
public void navback()
{
WebElement we = driver.findElement(By.xpath("//*[contains(#data-key,'electronics')]"));
Actions action = new Actions(driver);
action.moveToElement(we).build().perform();
}
#AfterClass
public void tear()
{
// driver.quit();
}
}
I want the tests to be like
FlipkartTest.java, FlipkartTest1.java and FlipkartTest2.java there in three different classes and the functions that I am using should be there in one common file - functions.java
public class Flipkart {
public static WebDriver driver;
#BeforeClass
public void beforeClass()
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30000, TimeUnit.MILLISECONDS);
}
#Test
public void FlipkartTest() throws InterruptedException
{
}
#Test
public void FlipkartTest1() throws InterruptedException
{
}
#Test
public void FlipkartTest2() throws InterruptedException
{
}
#AfterClass
public void tear()
{
// driver.quit();
}
}
and please let me know how to pass the driver instance to each of the tests.
You can create a Properties class. In that class you need to add a function with BeforeClass Annotation
public class Properties {
public static WebDriver driver;
#BeforeClass(alwaysRun=true)
public void LaunchBrowser()
{
driver = new FirefoxDriver();
}
}
Then you have to inherit properties class in your test classes
public class Flipkart1 entends Properties {}
public class Flipkart2 entends Properties {}
Related
feature file
Feature: Booking flight
Scenario: when user is onn the booking site
Given user select departure city
And user select destination city
And list of flights are shown to choose
Then choose the flight with lowest price
Scenario: when user had chosen the flight
Then user entered the following details
|Rohan|abcd hills|bangkok|tn|564329|American Express|1234000011119999|10|2024|Rohan Albert|
When user clicked on purchase flight
Then booking confirmation is displayed
base class:
package utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestBase {
public WebDriver driver;
public WebDriver webdrivermanager() throws IOException {
FileInputStream fis=new FileInputStream(System.getProperty("user.dir")+"\\src\\test\\resources\\global.properties");
Properties prop=new Properties();
prop.load(fis);
String url=prop.getProperty("url");
if(driver==null)
{
if(prop.getProperty("browser").equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\src\\test\\resources\\chromedriver.exe");
driver=new ChromeDriver();
}
driver.get(url);
}
return driver;
}
}
TestSetup cls:
package utils;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import pageobject.PageobjectManager;
public class TestSetup {
public WebDriver driver;
public PageobjectManager pageobjectmanager;
public TestBase testbase;
public TestSetup() throws IOException {
testbase=new TestBase();
pageobjectmanager=new PageobjectManager(testbase.webdrivermanager());
}
}
PageobjectManager:
package pageobject;
import org.openqa.selenium.WebDriver;
public class PageobjectManager {
public BookingPage bookingpage;
public ConfirmationPage confirmationpage;
public WebDriver driver;
public PageobjectManager(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver=driver;
}
public BookingPage getBookingPage() {
bookingpage=new BookingPage(driver);
return bookingpage;
}
public ConfirmationPage getConfirmationPage() {
confirmationpage=new ConfirmationPage(driver);
return confirmationpage;
}
}
Booking Page(pageobjects):
package pageobject;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public class BookingPage {
public WebDriver driver;
public BookingPage(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//select[#name='fromPort']")
WebElement departure;
#FindBy(xpath="//select[#name='toPort']")
WebElement destination;
#FindBy(xpath="//input[contains(#value,'Flights')]")
WebElement findflight;
#FindBy(xpath="//td[6]")
public List<WebElement> prices;
#FindBy(xpath="//tbody/tr[1]/td[1]")
WebElement flight1;
#FindBy(xpath="//tbody/tr[2]/td[1]")
WebElement flight2;
#FindBy(xpath="//tbody/tr[3]/td[1]")
WebElement flight3;
#FindBy(xpath="//tbody/tr[4]/td[1]")
WebElement flight4;
#FindBy(xpath="//tbody/tr[5]/td[1]")
WebElement flight5;
public void select_fromlist(String fromcity){
Select dropdown=new Select(departure);
dropdown.selectByVisibleText(fromcity);
}
public void select_tolist(String tocity){
Select dropdown=new Select(destination);
dropdown.selectByVisibleText(tocity);
}
public WebElement findingflight() {
return findflight;
}
public List<WebElement> pricing() {
//Double sum = 0.0;
for(int i = 0;i<prices.size();i++)
{
//double d=Double.parseDouble(prices.get(i).getText().replace("$", "").trim());
//System.out.println(d);
//System.out.println(Math.asin(d));
//Java.lang.math.min (d)
double d0=Double.parseDouble(prices.get(0).getText().replace("$", "").trim());
double d1=Double.parseDouble(prices.get(1).getText().replace("$", "").trim());
double d2=Double.parseDouble(prices.get(2).getText().replace("$", "").trim());
double d3=Double.parseDouble(prices.get(3).getText().replace("$", "").trim());
double d4=Double.parseDouble(prices.get(4).getText().replace("$", "").trim());
double min=Math.min(Math.min(d0, d1), Math.min(Math.min(d2, d3), d4));
System.out.println(min);
if(min==d0) {
flight1.click();
System.out.println("flight1 booked");
}
else if(min==d1) {
flight2.click();
System.out.println("flight2 booked");
}
else if(min==d2){
flight3.click();
System.out.println("flight3 booked");
}
else if(min==d3) {
flight4.click();
System.out.println("flight4 booked");
}
else
{
flight5.click();
System.out.println("flight5 booked");
}
}
return prices;
}
}
ConfirmationPage(Pageobject):
package pageobject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public class ConfirmationPage {
public WebDriver driver;
public ConfirmationPage(WebDriver driver) {
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//input[#id='inputName']")
WebElement name;
#FindBy(xpath="//input[#id='address']")
WebElement address;
#FindBy(xpath="//input[#id='city']")
WebElement city;
#FindBy(xpath="//input[#id='state']")
WebElement state ;
#FindBy(xpath="//input[#id='zipCode']")
WebElement zipcode ;
#FindBy(xpath="//select[#id='cardType']")
WebElement fcardtype ;
#FindBy(xpath="//input[#id='creditCardNumber']")
WebElement creditcardnumber ;
#FindBy(xpath="//input[#id='creditCardMonth']")
WebElement month ;
#FindBy(xpath="//input[#id='creditCardYear']")
WebElement year ;
#FindBy(xpath="//input[#id='nameOnCard']")
WebElement nameoncard ;
#FindBy(xpath="//input[#value='Purchase Flight']")
WebElement purchase ;
#FindBy(xpath="//div/h1")
WebElement confirmationtext ;
public WebElement Mname() {
return name;
}
public WebElement Maddress() {
return address;
}
public WebElement Mcity() {
return city;
}
public WebElement Mstate() {
return state;
}
public WebElement Mzipcode() {
return zipcode;
}
public void select_fromlist(String cardtype){
Select dropdown=new Select(fcardtype);
dropdown.selectByVisibleText(cardtype);
}
public WebElement Mcreditcardnumber() {
return creditcardnumber;
}
public WebElement Mmonth() {
return month;
}
public WebElement Myear() {
return year;
}
public WebElement Mnameoncard() {
return nameoncard;
}
public WebElement Mpurchase() {
return purchase;
}
public WebElement Mconfirmationtext() {
return confirmationtext;
}
}
StepDefinitions:
Bookingpage (stepdefinition1):
package stepdefiniton;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import pageobject.BookingPage;
import utils.TestSetup;
public class BookingSteps {
TestSetup testsetup;
public BookingPage bookingpage;
public BookingSteps(TestSetup testsetup) {
this.testsetup=testsetup;
this.bookingpage=testsetup.pageobjectmanager.getBookingPage();
}
#Given("^user select departure city$")
public void user_select_departure_city() throws Throwable {
bookingpage.select_fromlist("Boston");
}
#And("^user select destination city$")
public void user_select_destination_city() throws Throwable {
bookingpage.select_tolist("Rome");
}
#And("^list of flights are shown to choose$")
public void list_of_flights_are_shown_to_choose() throws Throwable {
bookingpage.findingflight().click();
}
#Then("^choose the flight with lowest price$")
public void choose_the_flight_with_lowest_price() throws Throwable {
bookingpage.pricing();
}
}
confirmationpage(stepdefinition2):
package stepdefiniton;
import java.util.List;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import pageobject.ConfirmationPage;
import utils.TestSetup;
public class ConfirmationSteps {
TestSetup testsetup;
public ConfirmationPage confirmationpage;
public ConfirmationSteps(TestSetup testsetup) {
this.testsetup=testsetup;
this.confirmationpage=testsetup.pageobjectmanager.getConfirmationPage();
}
//ConfirmationPage confirmationpage=new ConfirmationPage(null);
#Then("^user entered the following details$")
public void user_entered_the_following_details(DataTable data) throws Throwable {
List<List<String>> obj=data.asLists();
confirmationpage.Mname().sendKeys(obj.get(0).get(0));
confirmationpage.Maddress().sendKeys(obj.get(0).get(1));
confirmationpage.Mcity().sendKeys(obj.get(0).get(2));
confirmationpage.Mstate().sendKeys(obj.get(0).get(3));
confirmationpage.Mzipcode().sendKeys(obj.get(0).get(4));
confirmationpage.select_fromlist(obj.get(0).get(5));
confirmationpage.Mcreditcardnumber().sendKeys(obj.get(0).get(6));
confirmationpage.Mmonth().sendKeys(obj.get(0).get(7));
confirmationpage.Myear().sendKeys(obj.get(0).get(8));
confirmationpage.Mnameoncard().sendKeys(obj.get(0).get(9));
}
#When("^user clicked on purchase flight$")
public void user_clicked_on_purchase_flight() throws Throwable {
confirmationpage.Mpurchase().click();
}
#Then("^booking confirmation is displayed$")
public void booking_confirmation_is_displayed() throws Throwable {
confirmationpage.Mconfirmationtext().getText();
}
}
Testrunner class:
package testrunner;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
//import io.cucumber.testng.AbstractTestNGCucumberTests;
//import io.cucumber.testng.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(
features="src/test/java/features",
glue="stepdefiniton")
public class Testrunner {
}
//extends AbstractTestNGCucumberTests
The first stepdefinition is working fine,but when it comes to next stepdefinition file,its opening a new instance of the browser causing no such element exception.
why is the same instance not shared in the second stepdefinition file...what mistake am i doing...please help me out
While trying to run my test for the following code. I am getting some error detailed below.
I observed at the time it makes mkdirs() calls in my code throws IllegalArgumentException when I try to run my test.
MyClass.java
package com.javaeasily.demos.junit;
import java.util.ArrayList;
public class MyClass {
private final NodeHelper nodeHelper;
private static final ArrayList<String> ACTIVE_SERVICES_POST_RECONFIGURE = new ArrayList<>();
// Only allow construction if number is greater than one
MyClass() {
ACTIVE_SERVICES_POST_RECONFIGURE.add("my-node-" + NodeUtils.getMyNode());
nodeHelper = new NodeHelper();
}
public void reconfigureNode() {
if (ACTIVE_SERVICES_POST_RECONFIGURE.isEmpty()) {
return;
}
try {
nodeHelper.createStagingDir();
} catch (Exception e) {
throw new RuntimeException("Cannot reconfigure node");
}
}
}
NodeUtils.java
package com.javaeasily.demos.junit;
import org.apache.commons.lang3.StringUtils;
public class NodeUtils {
private static final String HOSTNAME_PREFIX = "my-node-";
public static String hostnameToNode(String hostname) {
if (!hostname.startsWith(HOSTNAME_PREFIX)) {
throw new IllegalArgumentException(hostname + " is not recognized hostname");
}
return StringUtils.removeStart(hostname, HOSTNAME_PREFIX);
}
public static String getHostname() {
return System.getenv("HOSTNAME");
}
public static String getMyNode() {
return hostnameToNode(getHostname());
}
}
NodeHelper.java
package com.javaeasily.demos.junit;
import java.io.File;
public class NodeHelper {
private static final String STAGING_DIR = "/staging/";
public void createStagingDir() {
File stagingDir = new File(STAGING_DIR);
if (!stagingDir.exists() && !stagingDir.mkdirs()) {
throw new IllegalArgumentException("Could not create staging dir");
}
}
}
MyClassTest.java
package com.javaeasily.demos.junit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
#ExtendWith(MockitoExtension.class)
public class MyClassTest {
private MyClass myclass;
#BeforeEach
public void SetUp() {
try (MockedStatic<NodeUtils> nodeUtilsMockedStatic = Mockito.mockStatic(NodeUtils.class);) {
nodeUtilsMockedStatic.when(NodeUtils::getMyNode).thenReturn("foo");
myclass = new MyClass();
}
}
#Test
public void testReconfigureNode() {
myclass.reconfigureNode();
}
}
When I try to run my test I get following error:
java.lang.RuntimeException: Cannot reconfigure node
at com.javaeasily.demos.junit.MyClass.reconfigureNode(MyClass.java:22)
Post debugging I see that:
java.lang.IllegalArgumentException: Could not create staging dir
Does anyone care to enlighten me as to what I am doing wrong?
To mock NodeHelper you should not create it inside MyClass, but inject it from the outside via the constructor. i.e.
MyClass(Nodehelper nodeHelper) {
ACTIVE_SERVICES_POST_RECONFIGURE.add("my-node-" + NodeUtils.getMyNode());
this.nodeHelper = nodeHelper;
}
This allows you to create a mocked NodeHelper in your test, pass it to MyClass and set the desired behavior as expectations.
I have two pages, in one everything is fine, but in the other I get java.lang.NullPointerException
What is my mistake? Please help
LoginPage.java - all good
package page;
import Base.Base;;
import paths.LoginPath;
public class LoginPage extends Base {
LoginPath loginPath = new LoginPath();
public void ingresarPagina(){
chromeDriverConnection();
visit(loginPath.url);
maximize();
}
public void iniciarSesion(){
type("Qualityadmin", loginPath.txtUser);
type("pass1", loginPath.txtPass);
}
public void clickEnBoton(){
click(loginPath.btnLogin);
}
}
HomePage.java - I tried placing the chromeDriverConnection() again, but I get the same error
package page;
import Base.Base;
import paths.HomePath;
public class HomePage extends Base {
HomePath homePath = new HomePath();
public void mensajeExitoso() {
String mensaje = getText(homePath.txtMesajeExito);
System.out.println(mensaje);
}
}
Error
java.lang.NullPointerException
at Base.Base.getText(Base.java:35)
at page.HomePage.mensajeExitoso(HomePage.java:12)
at step.HomeStep.mensajeExitoso(HomeStep.java:10)
at stepdefinition.HomeStepDefinition.seMuestraUnMensajeDeExito(HomeStepDefinition.java:11)
at ✽.se muestra un mensaje de exito(file:///D:/Project/aer/features/src/test/resources/features/formulario.feature:22)
Process finished with exit code -1
Base.java - I don't think the error is in the Base class, but I put it anyway
Line 35: return driver.findElement (locator) .getText ();
When I put the mensajeExitoso() method in the LoginPage class everything goes fine
package Base;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Base {
public WebDriver driver;
public Base(WebDriver driver){
this.driver = driver;
}
public Base() {
}
public WebDriver chromeDriverConnection() {
System.setProperty("webdriver.chrome.driver", "./src/test/resources/drivers/chromedriver.exe");
driver = new ChromeDriver();
return driver;
}
public WebElement findElement(By locator){
return driver.findElement(locator);
}
public String getText(WebElement element){
return element.getText();
}
public String getText(By locator){
return driver.findElement(locator).getText();
}
public void type(String inputText, By locator){
driver.findElement(locator).sendKeys(inputText);
}
public void iniciarSesion(String user, String pass){
}
public void click(By locator){
driver.findElement(locator).click();
}
Double num1 = 20.00;
String num2 = num1.toString();
public void visit(String url){
driver.get(url);
}
public void isDisplayed(By locator){
driver.findElement(locator).isDisplayed();
}
public void maximize(){
driver.manage().window().maximize();
}
}
You tried
chromeDriverConnection();
String mensaje = getText(homePath.txtMesajeExito);
System.out.println(mensaje);
right? and can you show me see homePath.txtMesajeExito
Hi community: Trying to integrate Cucumber with JUnit, I have the next class.
import cl.cukes.ParameterizedRunnerFactory;
import cl.test.AutomatedWebTest;
import cl.util.report.Report;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.UseParametersRunnerFactory;
import org.junit.runners.model.InitializationError;
import org.junit.runners.parameterized.TestWithParameters;
import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
//JAVA
#RunWith(Parameterized.class)
#UseParametersRunnerFactory(ParameterizedRunnerFactory.class)
public class CucumberStepDefs extends AutomatedWebTest {
#Parameterized.Parameter(value = 0)
public String user;
#Parameterized.Parameter(value = 1)
public String pass;
public static class CucumberRunnerFactor extends ParameterizedRunnerFactory {
public Runner createRunnerForTestWithParameters(TestWithParameters test)
throws InitializationError {
try {
return new Cucumber(test.getTestClass().getJavaClass());
} catch (IOException e) {
throw new InitializationError(e);
}
}
}
#Given("^Enter to the QA URL environment")
public void Login() throws Exception {
baseUrl = "http://www.miprivado.cl/";
driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl + "ucachaca/test.htm");
driver.switchTo().defaultContent();
driver.switchTo().frame("frmbody");
}
#When("^Fields Username y Passwordare displayed so enter parameters$")
public void UsuarioPass() throws Exception {
driver.findElement(By.id("TxbTELLUSERID")).clear();
driver.findElement(By.id("TxbTELLUSERID")).sendKeys(user);
driver.findElement(By.id("TxbUSERPASSW")).clear();
driver.findElement(By.id("TxbUSERPASSW")).sendKeys(pass);
screenshot.take(this, driver, "LoginR C01");
driver.findElement(By.id("BtnSubmit")).click();
driver.switchTo().defaultContent();
driver.switchTo().frame("frmwebteller");
driver.manage().window().maximize();
}
#Then("^User gets into the system and do Logout Logout$")
public void Logout() throws Exception {
screenshot.take (this, driver, "LoginR C02");
driver.switchTo ().defaultContent ();
driver.switchTo ().frame ("frmbody").switchTo ().frame ("menu");
driver.findElement(By.cssSelector("b")).click();
screenshot.take (this, driver, "LoginR C03");
driver.findElement(By.linkText("Log Off")).click();
screenshot.take (this, driver, "LoginR C04");
driver.quit();
}
}
The ParameterizedRunnerFactory is the next:
import org.junit.runner.Runner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.parameterized.ParametersRunnerFactory;
import org.junit.runners.parameterized.TestWithParameters;
/**
*
*/
public class ParameterizedRunnerFactory implements ParametersRunnerFactory {
#Override
public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
return new ParameterizedRunner(test);
}
}
The parameterized Runner class is the next:
import org.junit.After;
import org.junit.Before;
import org.junit.runners.model.*;
import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
import org.junit.runners.parameterized.TestWithParameters;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class ParameterizedRunner extends BlockJUnit4ClassRunnerWithParameters {
public ParameterizedRunner(TestWithParameters test) throws InitializationError {
super(test);
}
// workaround for: https://github.com/junit-team/junit/issues/1046
private static final ConcurrentHashMap<Class<?>, TestClass> testClasses = new ConcurrentHashMap<>();
#Override
protected TestClass createTestClass(Class<?> clazz) {
TestClass testClass = testClasses.get(clazz);
if (testClass == null) {
testClasses.put(clazz, testClass = new TestClass(clazz));
}
return testClass;
}
// playing whack-a-mole with new TLAB allocations by re-defining with{Befores,Afters}...
#Override
protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) {
List<FrameworkMethod> list = getTestClass().getAnnotatedMethods(Before.class);
if (list.isEmpty()) {
return statement;
}
return new BeforesStatement(target, statement, list);
}
#Override
protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) {
List<FrameworkMethod> list = getTestClass().getAnnotatedMethods(After.class);
if (list.isEmpty()) {
return statement;
}
return new AftersStatement(target, statement, list);
}
private static final class BeforesStatement extends Statement {
private static final Object[] EMPTY_ARGS = new Object[0];
private final Object target;
private final Statement statement;
private final List<FrameworkMethod> list;
BeforesStatement(Object target, Statement statement, List<FrameworkMethod> list) {
this.target = target;
this.statement = statement;
this.list = list;
}
#Override
public void evaluate() throws Throwable {
// (1) Avoid ImmutableCollections#iterator()
for (int i = 0, size = list.size(); i < size; ++i) {
list.get(i).invokeExplosively(target, EMPTY_ARGS);
}
statement.evaluate();
}
}
private static final class AftersStatement extends Statement {
private static final Object[] EMPTY_ARGS = new Object[0];
private final Object target;
private final Statement statement;
private final List<FrameworkMethod> list;
AftersStatement(Object target, Statement statement, List<FrameworkMethod> list) {
this.target = target;
this.statement = statement;
this.list = list;
}
#Override
public void evaluate() throws Throwable {
// (2) Lazily create ArrayList
ArrayList<Throwable> throwables = null;
try {
statement.evaluate();
} catch (Throwable e) {
throwables = new ArrayList<Throwable>();
throwables.add(e);
} finally {
for (int i = 0, size = list.size(); i < size; ++i) {
try {
list.get(i).invokeExplosively(target, EMPTY_ARGS);
} catch (Throwable e) {
if (throwables == null) {
throwables = new ArrayList<Throwable>();
}
throwables.add(e);
}
}
}
if (throwables != null) {
MultipleFailureException.assertEmpty(throwables);
}
}
}
}
The Cucumber Runner Test class is the next:
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(features={"//src/features/Login.feature"}
,format = {"pretty", "html:target/cucumber"}
,glue = {"cucumber.CucumberStepDefs"}
)
/*#Suite.SuiteClasses({
CucumberStepDefs.class,
})*/
public class CucumberRunnerTest {
}
When I run my CucumberStepDefs, it displays the next issue on IntelliJ:
java.lang.Exception: No public static parameters method on class cl.cucumber.CucumberStepDefs
All the classes don't show error, but I'm not able to run this class.
Could anybody help me with this?
Don't try to mix JUnit with Maven:
The best answer were done by Grasshopper:
1.- Create the Feature file.
2.- Use Scenario Outline and put the data in Examples section.
3.- Use a runner like next:
#CucumberOptions(features = {"src/test/resource/features"},
glue={"stepdefs"},
monochrome = true,
tags = {"~#Ignore"},
plugin = {"pretty","html:target/cucumber-reports/cucumber-pretty",
"json:target/cucumber-reports/CucumberTestReport.json",
"rerun:target/cucumber-reports/rerun.txt",
"usage:target/cucumber-usage.json"}
)
public class TestRunner extends ExtendedTestNGRunner{
private TestNGCucumberRunner testNGCucumberRunner;
#BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
#Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature) {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
#DataProvider
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
}
#AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
}
And run the Feature.
Thanks a lot, Grasshopper!!!
I'm trying to encapsulate a Selenium script by breaking it up into three classes (Grid, Browser, and testCase). I'm able to get the browser to open, but I seem to be missing the connection for the testCase class to interject its commands.
Grid.java
package com.autotrader.grid;
import org.junit.After;
import org.junit.Test;
public class Grid {
Browser browser = new Browser();
TestCase testCase = new TestCase();
public Grid() {
browser.setUp("http://pbskids.org");
}
#Test
public void main() {
testCase.runCase();
}
#After
public void tearDown() throws Exception {
browser.stop();
}
}
Browser.java
package com.autotrader.grid;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.util.concurrent.TimeUnit;
public class Browser {
private String baseUrl;
private String driverNamespace;
private String driverLocation;
private DesiredCapabilities capabilities;
private WebDriver driver;
public Selenium selenium;
// constructor
public Browser() {
}
public DesiredCapabilities getCapabilities() {
return this.capabilities;
}
public String getDriverLocation() {
return this.driverLocation;
}
public String getDriverNamespace() {
return this.driverNamespace;
}
public Selenium getSelenium(){
return selenium;
}
public void open (String url) {
this.selenium.open(url);
}
public void setBaseUrl(String url) {
this.baseUrl = url;
}
public void setCapabilities() {
this.capabilities = DesiredCapabilities.firefox();
this.driver = new FirefoxDriver(capabilities);
}
public void setDriverLocation(String location) {
this.driverLocation = location;
}
public void setDriverNamespace(String namespace) {
this.driverNamespace = namespace;
}
public void setSpeed(String speed){
this.selenium.setSpeed(speed);
}
public void setUp(String url){
setDriverNamespace("webdriver.firefox.driver");
setDriverLocation(System.getenv("ProgramFiles(x86)") + "\\Mozilla Firefox\\firefox.exe");
System.setProperty(driverNamespace,driverLocation);
setCapabilities();
setBaseUrl(url);
this.selenium = new WebDriverBackedSelenium(driver, url);
this.driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public void stop(){
this.selenium.stop();
}
}
TestCase.java
package com.autotrader.grid;
import com.thoughtworks.selenium.Selenium;
public class TestCase {
Browser browser = new Browser();
Selenium selenium;
// constructor
public TestCase(){
selenium = browser.getSelenium();
}
public void runCase(){
selenium.open("/privacy/termsofuse.html?campaign=fkhp_tou");
selenium.setSpeed("1000");
}
}
So; the driver is setup, I then opened using the Selenium object (in Browser.java), but when I try to interact with the Selenium object (in TestCase.java) it's not picking it up. Thank you for any help.
Instead of:
public class Grid {
Browser browser = new Browser();
TestCase testCase = new TestCase();
public Grid() {
...
Try:
public class Grid {
Browser browser = new Browser();
TestCase testCase = new TestCase(browser); // <-- this line changed
public Grid() {
...
And in here:
public class TestCase {
Browser browser = new Browser();
Selenium selenium;
// constructor
public TestCase(){
selenium = browser.getSelenium();
}
...
Do like this:
public class TestCase {
Browser browser = new Browser(); // <-- this line changed
Selenium selenium;
// constructor
public TestCase(Browser browser){ // <-- this line changed
this.browser = browser; // <-- this line was added
selenium = browser.getSelenium();
}
...
I don't see that you're ever initializing your Selenium object except for in Browser's setUp(String url) method. And that method is also not being called here.
You've also made your Browser's Selenium object public, so you don't need to declare another Selenium object in TestCase that's assigned by an accessor method -- you can just reference it from TestCase's Browser object.