I first created a POM model framework for a test practice with LOG4J, listners for Screenshots.
Later tried to add Cucumber BDD framework also into the same framework. I'm able to run the tests as expected, but facing two issues:
POM Framework initial tests are able to take Screenshots, but BDD test fails with Null pointer exception, unable to get the driver object from the Methods.
Logs not getting printed for BDD tests while works fine with POM tests.
Code
TestRunner.java
package cucumberRunner;
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="stepDefinitions")
public class TestRunner extends AbstractTestNGCucumberTests {
}
MyStepDefinitions.java
package stepDefinitions;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import e2E4.UserLogins;
import pageObjects.LandingPage;
import pageObjects.LoggedOnPage;
import resources.BaseClass;
public class MyStepDefinitions extends BaseClass {
public WebDriver driver;
Logger log=LogManager.getLogger(UserLogins.class.getName());
#Given("^Initialize browser with Chrome$")
public void initialize_browser_with_Chrome() throws Throwable {
driver = driverIni();
}
#Given("^Navigate to \"([^\"]*)\" website$")
public void navigate_to_saucelabs_website(String arg1) throws Throwable {
driver.get(arg1);
}
#When("^User enters \"([^\"]*)\" and \"([^\"]*)\" and Logs in$")
public void user_enters_and_and_Logs_in(String arg1, String arg2) throws Throwable {
LandingPage lp=new LandingPage(driver);
lp.sendUsername().sendKeys(arg1);
lp.sendPassword().sendKeys(arg2);
lp.sendLoginBtn().click();
log.info("Logging in");
}
#Then("^Verify if user successfully logged in$")
public void verify_if_user_successfully_logged_in() throws Throwable {
LoggedOnPage lop=new LoggedOnPage(driver);
Assert.assertTrue(lop.filterbtn().isDisplayed());
log.info("Logged in successfully");
}
}
BaseClass.java
package resources;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class BaseClass {
public WebDriver driver;
public Properties prop;
String dataPath=System.getProperty("user.dir");
public WebDriver driverIni() throws IOException {
FileInputStream fis=new FileInputStream(dataPath+"\\src\\main\\java\\resources\\data.properties");
prop=new Properties();
prop.load(fis);
String browserRequired=prop.getProperty("browser");
if(browserRequired.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", dataPath+"\\chromedriver.exe");
driver=new ChromeDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
return driver;
}
public String screenshot(String methodName, WebDriver driver) throws IOException {
TakesScreenshot ts=(TakesScreenshot) driver;
File source=ts.getScreenshotAs(OutputType.FILE);
String dest=dataPath+"\\reports\\"+methodName+".png";
FileUtils.copyFile(source, new File(dest));
return dest;
}
}
Listners.java
package e2E4;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import resources.BaseClass;
import resources.ExtendRep;
public class Listners extends BaseClass implements ITestListener {
WebDriver driver=null;
ExtendRep er=new ExtendRep();
ExtentReports extent=er.getReports();
ExtentTest test;
ThreadLocal<ExtentTest> et=new ThreadLocal<ExtentTest>();
public void onTestStart(ITestResult result) {
test=extent.createTest(result.getMethod().getMethodName());
et.set(test);
}
public void onTestSuccess(ITestResult result) {
String methodName=result.getMethod().getMethodName();
et.get().log(Status.PASS, "Test Passed Successfully");
try {
driver=(WebDriver)result.getTestClass().getRealClass().getDeclaredField("driver").get(result.getInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
et.get().addScreenCaptureFromPath(screenshot(methodName,driver),result.getMethod().getMethodName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onTestFailure(ITestResult result) {
String methodName=result.getMethod().getMethodName();
et.get().fail(result.getThrowable());
try {
driver=(WebDriver)result.getTestClass().getRealClass().getDeclaredField("driver").get(result.getInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
et.get().addScreenCaptureFromPath(screenshot(methodName,driver),result.getMethod().getMethodName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onTestSkipped(ITestResult result) {
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
public void onTestFailedWithTimeout(ITestResult result) {
}
public void onStart(ITestContext context) {
}
public void onFinish(ITestContext context) {
extent.flush();
}
}
P.S : ExtentReports were working fine tho throu the Listners. Not able to figure it out :(
Related
I try to run an automation on notepad file on windows via winnap driver.
and I get : "FAILED CONFIGURATION: #BeforeMethod setUp
org.openqa.selenium.WebDriverException: Connection refused: no further
information"
What is can be ?
JAVA :
package com.mytest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.appium.java_client.windows.WindowsDriver;
public class NotePadTest {
public static WindowsDriver driver = null ;
#BeforeMethod
public void setUp() {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("app","C:\\Windows\\System32\\notepad.exe");
cap.setCapability( "platform", "Windows");
cap.setCapability( "deviceName", "WindowsPC");
try {
driver = new WindowsDriver(new URL("http://127.0.0.1:4723"), cap);
} catch (MalformedURLException e) {
// TODO: handle exception
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
#AfterMethod
public void clenUp() {
driver.quit();
setUp();
}
#AfterSuite
public void tearDown() {
driver.quit();
}
#Test
public void checkHelpAboutNowTest() {
driver.findElementByName("App theme").click();
}
}
Im writing a selenium project from scratch using the PageObject.
The below code is failing because the selenium webdriver is not finding elements on the webpage .
This is the error i get :
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null
DriverBase.java :
In this class i setup the driver
package com.EbankingA11y.base;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import com.EbankingA11y.util.WebListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class DriverBase {
protected static final Logger LOG = (Logger) LogManager.getLogger(WebListener.class);
public static WebDriver driver;
public static Properties prop;
public static FileInputStream fis;
public DriverBase() {
prop = new Properties();
try {
fis = new FileInputStream("C:\\Users\\config.properties");
} catch (FileNotFoundException exception) {
exception.printStackTrace();
LOG.debug(" Error \n " +exception.getStackTrace());
}
try {
prop.load(fis);
} catch (IOException exception) {
exception.printStackTrace();
LOG.debug(" Error \n " +exception.getStackTrace());
}
}
public static void initialization () throws InterruptedException {
System.setProperty("webdriver.chrome.driver", prop.getProperty("WEB_DRIVER_PATH") );
//WebDriverManager.chromedriver().setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setAcceptInsecureCerts(true);
driver = new ChromeDriver(chromeOptions);
driver.manage().window().maximize();
driver.get(prop.getProperty("URL"));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
LoginPage.java
In this class i create all the element on the login page and all methods
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.EbankingA11y.base.DriverBase;
public class LoginPage extends DriverBase {
public LoginPage() {
PageFactory.initElements(DriverBase.driver, this);
}
#FindBy(name="username")
WebElement usernameTextBox;
#FindBy(name="password")
WebElement passwordTextBox;
#FindBy(xpath="//input[#value=\\\"Use 'Enter' to confirm\\\"]")
WebElement submitButton;
#FindBy(xpath="//button[#name='button']")
WebElement languageButton;
#FindBy(name="smsCode")
WebElement tokenTextBox;
public void performLogin () {
//WebDriverWait wait = new WebDriverWait(driver,30);
final String username = prop.getProperty("USERNAME");
final String password = prop.getProperty("PASSWORD");
System.out.println(username);
//wait.until(ExpectedConditions.visibilityOf(this.usernameTextBox));
usernameTextBox.clear();
passwordTextBox.clear();
usernameTextBox.sendKeys(username);
passwordTextBox.sendKeys(password);
submitButton.click();
//wait.until(ExpectedConditions.visibilityOf(this.tokenTextBox));
}
}
LoginPageTests.java :
In this class i write tests and i call methods from LoginPage.java Class
package com.EbankingA11y.testcases;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.EbankingA11y.base.*;
import com.EbankingA11y.pages.LoginPage;
public class LoginPageTest extends DriverBase {
public LoginPageTest() throws IOException {
super();
}
LoginPage loginPage = new LoginPage();
#BeforeTest
public void setup() throws InterruptedException {
initialization();
}
#Test
public void login() {
loginPage.performLogin();
}
}
I found that i have to declare the pages in the before methods after the initilisation ()
public class LoginPageTest extends DriverBase {
public LoginPageTest() throws IOException {
super();
}
// here
LoginPage loginPage;
TokenPage tokenPage;
#BeforeTest
public void setup() throws InterruptedException {
initialization();
//here
loginPage = new LoginPage();
tokenPage = new TokenPage();
}
#Test
public void login() {
tokenPage = loginPage.performLogin();
}
}
This is just worked for me
i have tried to "wait 1 second" in minecraft forge and i use "Thread" to do it.
But i got this error.
Exception in thread "Thread-14" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:218)
at io.github.bloodnighttw.WaitAndReplaceBlock.run(WaitAndReplaceBlock.java:22)
i have tried to use world.scheduleBlockUpdate(......) to do it,but anything happened after i break block.
And this is my code,there have three class.
ExampleMod.java
package io.github.bloodnighttw;
import net.minecraft.init.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.Logger;
import io.github.bloodnighttw.event.Event;
#Mod(modid = ExampleMod.MODID, name = ExampleMod.NAME, version = ExampleMod.VERSION)
public class ExampleMod
{
public static final String MODID = "nothing";
public static final String NAME = "Bang!";
public static final String VERSION = "3.0";
private static Logger logger;
#EventHandler
public void preInit(FMLPreInitializationEvent event)
{
logger = event.getModLog();
logger.info("Bang");
}
#EventHandler
public void init(FMLInitializationEvent event)
{
// some example code
logger.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
MinecraftForge.EVENT_BUS.register(new Event());
}
}
Event.java
package io.github.bloodnighttw.event;
import io.github.bloodnighttw.WaitAndReplaceBlock;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class Event {
#SubscribeEvent
public void breakBlockEvent(final BreakEvent e) {
e.getPlayer().sendMessage(new TextComponentString(e.getState().toString()+"222222"));
BlockPos a = e.getPos();
new WaitAndReplaceBlock(a,e).start();
}
}
WaitAndReplaceBlock.java
package io.github.bloodnighttw;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.event.world.BlockEvent;
public class WaitAndReplaceBlock extends Thread{
BlockPos a;
BlockEvent.BreakEvent e ;
public WaitAndReplaceBlock(BlockPos a, BlockEvent.BreakEvent e){
this.a = a ;
this.e = e ;
}
#Override
public void run() {
try {
wait(10);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
World world = e.getWorld();
world.setBlockState(a, Blocks.BEDROCK.getDefaultState());
}
}
i have tried to google it,but everything i search is too old to be use in 1.12.2 or it is not a solution to me,so i decided to ask in stackoverflow.
Edit:
This is the code that i used world.scheduleBlockUpdate(......)
Only Event.java have some change.
Event.java
package io.github.bloodnighttw.event;
import io.github.bloodnighttw.WaitAndReplaceBlock;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class Event {
#SubscribeEvent
public void breakBlockEvent(final BreakEvent e) {
e.getPlayer().sendMessage(new TextComponentString(e.getState().toString()+"222222"));
BlockPos a = e.getPos();
//new WaitAndReplaceBlock(a,e).start();
e.getWorld().scheduleBlockUpdate(a,e.getState().getBlock(),10,1000000);
}
}
And this is what i said "Nothing happened".
Video: https://youtu.be/tZMIRHDUnV4
Using Robotium for my Android automation I find myself creating the same steps for each test case.
I always need to "Login" and "Logout", I've been trying to create a FunctionsTestClass so I can simply call rLogin(); and rLogout();
Here is an example:
Adding my complete files.
'package com.myproject.mobile.test;
import android.test.ActivityInstrumentationTestCase2;
import android.app.Activity;
import junit.framework.AssertionFailedError;
import com.bitbar.recorder.extensions.ExtSolo;
import com.jayway.android.robotium.solo.By;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
'public class Logout extends ActivityInstrumentationTestCase2<Activity> {
private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.myproject.mobile.MainActivity";
private static Class<?> launchActivityClass;
static {
try {
launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps
// collecting better test execution data during test
// runs
#SuppressWarnings("unchecked")
public Logout() {
super((Class<Activity>) launchActivityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
.getCanonicalName(), getName());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
solo.tearDown();
super.tearDown();
}
public static void logginin() throws Exception {
try {
//enter username
solo.sleep(17000);
throw e;
} catch (Exception e) {
solo.fail(
"com.myproject.mobile.test.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
}
}
}'
Adding my second file
package com.mypackage.mobile.test;
import android.test.ActivityInstrumentationTestCase2;
import android.app.Activity;
import junit.framework.AssertionFailedError;
import com.bitbar.recorder.extensions.ExtSolo;
import com.jayway.android.robotium.solo.By;
import com.mypackage.mobile.test.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
'public class Test extends ActivityInstrumentationTestCase2<Activity> {
private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.mypackage.mobile.MainActivity";
private static Class<?> launchActivityClass;
static {
try {
launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps
// collecting better test execution data during test
// runs
#SuppressWarnings("unchecked")
public Test() {
super((Class<Activity>) launchActivityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
.getCanonicalName(), getName());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
solo.tearDown();
super.tearDown();
}
public void testRecorded() throws Exception {
try {
Logout.logginin();
} catch (AssertionFailedError e) {
solo.fail(
"com.mypackage.name.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
} catch (Exception e) {
solo.fail(
"com.mypackage.name.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
}
}
}
Updated the bottom two code to reflect my project.
Don't create testcase with name testLoggingin() . Instead of that creat a class having function login(). So that, whenever its needed you can import it and can call the function to login. And you can check conditions using assert.
I have successfully created a data driven framework with selenium 1 and trying to do the same using selenium 2 (WebDriver). I was doing some basic R and D. My code is as below.
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;
import org.testng.annotations.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import jxl.*;
#SuppressWarnings("unused")
public class FirstTestusingWebDriver {
private WebDriver driver;
private String baseUrl="http://www.google.co.in";
private StringBuffer verificationErrors = new StringBuffer();
#BeforeClass
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#DataProvider(name="DP")
Object[] createData(){
String[] testData = {"Cheese", "Sudeep"};
System.out.println("Data is getting created");
return testData;
}
#Test(dataProvider="DP")
public void testUntitled(String testData) throws Exception {
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).clear();
driver.findElement(By.id("lst-ib")).sendKeys(testData);
driver.findElement(By.name("btnG")).click();
driver.findElement(By.linkText("Cheese - Wikipedia, the free encyclopedia")).click();
}
#AfterClass
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;
}
}
}
But with this code, the test is not running. Firefox opens and closes while running the test as testNG. Can anyone suggest a proper way to go about it or how to make this work.
just do a slight amendment in ur createData() i.e
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;
import org.testng.annotations.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
#SuppressWarnings("unused")
public class FirstTestusingWebDriver {
private WebDriver driver;
private String baseUrl="http://www.google.co.in";
private StringBuffer verificationErrors = new StringBuffer();
#BeforeClass
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#DataProvider(name="DP")
Object[][] createData(){
String[] testData = {"Cheese", "Sudeep"};
System.out.println("Data is getting created");
return new Object[][]{{testData[0]+testData[1]}};
}
#Test(dataProvider="DP")
public void testUntitled(String testData) throws Exception {
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).clear();
driver.findElement(By.id("lst-ib")).sendKeys(testData);
driver.findElement(By.name("btnG")).click();
//driver.findElement(By.linkText("Cheese - Wikipedia, the free encyclopedia")).click();
}
#AfterClass
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;
}
}}
now it will work fine..