I did a basic project to training about Page Objects using selenium WebDriver with java and Junit. So, I make a page object class and Junit class too. I Make a call of method and pass the parameters to method but, the eclipse show a message that say: java.lang.NullPointerException
public class LogarBkoMaisPage {
static WebDriver driver;
By campoNome = By.id("matricula_I");
By campoSenha = By.id("senha_I");
By btnLogin = By.id("bt_entrar");
public LogarBkoMaisPage(WebDriver driver) {
this.driver = driver;
}
public void logar(String usuario, String senha) {
driver.findElement(campoNome).sendKeys(usuario);
driver.findElement(campoSenha).sendKeys(senha);
driver.findElement(btnLogin).click();
}
}
public class LogarBkoMaisTest {
static WebDriver driver;
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
nav.iniciarNavegador("ie","http://10.5.9.45/BkoMais_Selenium/");
}
#Test
public void logarAplicacao() {
try {
LogarBkoMaisPage login = new LogarBkoMaisPage(driver);
login.logar("844502","Bcc201707");
}catch(Exception e) {
System.out.println("Mensagem de erro: " +e);
}
}
#After
public void tearDown() throws Exception {
}
}
public class SelecionarNavegador {
static WebDriver driver;
public static WebDriver iniciarNavegador(String nomeNavegador, String url) {
if(nomeNavegador.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "E:\\workspace_BCC_QA_BKOMAIS\\"
+ "FireFoxGeckodriver64\\geckodriver.exe");
driver = new FirefoxDriver();
}
else if(nomeNavegador.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "E:\\workspace_BCC_QA_BKOMAIS"
+ "\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}else if(nomeNavegador.equalsIgnoreCase("IE")) {
System.setProperty("webdriver.ie.driver", "E:\\workspace_BCC_QA_BKOMAIS"
+ "\\IE Plugin\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
Exception:
You are getting a null pointer exception because iniciarNavegador method inside SelecionarNavegador class is the one which initializes the driver and it returns the driver which has to be assigned to a vairable. You need to do this in your setUp()method
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
driver=nav.iniciarNavegador("ie","http://10.5.9.45/BkoMais_Selenium/");
}
Related
I am running a test case using pagefactory method and have created an appium driver. I'm trying to initialising a page using pagefactory class like this:
The test class:
public class VerifyValidLogin {
#Test
public void CheckValidUser() throws MalformedURLException {
AppiumDriver driver = DeviceFactory.CreateDriver();
login login_page = PageFactory.initElements(driver, login.class);
}
}
DeviceFactory class:
public class DeviceFactory {
public static AppiumDriver<MobileElement> driver;
public static AppiumDriver CreateDriver() throws MalformedURLException {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability( capabilityName: 'deviceName', value: 'Something');
...
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AppiumDriver<MobileElement>(url,cap);
System.out.print("Application started");
return driver;
}
}
Login class has element locators:
public class login {
AppiumDriver driver;
public login(AppiumDriver ldriver)
{
this.driver=ldriver;
}
#FindBy(how = How.XPATH,using ="xpath");
MobileElement SignInButton;
}
But i'm not sure where i am doing wrong.
The error is
java.lang.RuntimeException: java.lang.InstantiationException: com.Demo.pages.login
at org.openqa.selenium.support.PageFactory.instantiatePage(PageFactory.java:134)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:64)
at com.Demo.Testcases.VerifyValidLogin.CheckValidUser(VerifyValidLogin.java:18)
...
I am new to the automation testing so i'm not able to properly understand the error. Let me know if you need more details.
Initialise elements in constructor
public login(AppiumDriver ldriver)
{
this.driver=ldriver;
PageFactory.initElements(ldriver,this);
}
to all.
Curently writing a little BDD Test automation framework, using Java11+Junit5+Cucumber+Selenium, build tool: Graddle. Created a little test for validating Google title. When starting test, using Test task in Graddle or running CucumberRunner class, in both cases getting the same result: two times #Before method is executed, once #After method is executed and one browser windows is staying open. After added one more test, the same situation, only 4 browsers are opened, 2 of them are closing. Can anyone help with this situation?
Link to repository
After some watching of logs saw, that, seems, #Before is not executed twice, but Driver class is initialized twice, but why it happens no idea for now...
My code for now:
CucumberRunner.java:
#RunWith(Cucumber.class )
#CucumberOptions(
features = "src\\test\\java\\features",
glue = {"steps", "utils"},
tags = "#smoke")
public class CucumberRunner {
}
Driver.java:
public class Driver {
private WebDriver driver;
public Driver(){
driverInitialization();
}
private void driverInitialization(){
System.setProperty("webdriver.chrome.driver", "D:\\Soft\\selenium-drivers\\chromedriver.exe");
System.out.println("Starting driver.");
var browserName = "chrome";
switch (browserName.toLowerCase()){
case "chrome":
System.out.println("Starting chrome");
driver = new ChromeDriver();
System.out.println("Before break.");
break;
case "firefox":
driver = new FirefoxDriver();
break;
default:
throw new NotFoundException("Browser not found: " + browserName);
}
}
public WebDriver getDriver(){
return driver;
}
public WebDriverWait getWebDriverWait(){
return new WebDriverWait(driver, 120);
}
public void terminateDriver(){
System.out.println("Terminating driver.");
if (driver != null) {
driver.close();
driver.quit();
}
}
}
Hooks.java:
public class Hooks {
private Driver driver;
#Before
public void setup(){
System.out.println("In the Setup method.");
driver = new Driver();
}
#After
public void tearDown(){
System.out.println("In the TearDown method.");
driver.terminateDriver();
}
}
I think your Hook Class should be like this As You Are Using selenium-picocontainer DI.
public class Hooks {
private Driver driver;
public Hooks(Driver driver) {
this.driver = driver;
}
#Before
public void setup(){
System.out.println("In the Setup method.");
}
#After
public void tearDown(){
System.out.println("In the TearDown method.");
driver.terminateDriver();
}
}
I am trying to implement Page Object with annotation #FindBy in class Select. In Eclipse it's showing following a message:
the method id(String) in the type By is not applicable for the arguments (WebElement).
I do not why this message comes. Follow below the code and image of error.
Class FaturamentoGeTratamentoOsPage
public class FaturamentoGeTratamentoOsPage {
WebDriver driver;
#FindBy(id = "cboMotivo")
WebElement CBOMotivo;
public FaturamentoGeTratamentoOsPage(WebDriver driver) {
this.driver = driver;
}
public void preencherCampoMotivo(String CampoMotivo) {
// Campo Motivo
WebElement campoMotivo = driver.findElement(By.id(CBOMotivo));
Select slcMotivo = new Select(campoMotivo);
slcMotivo.selectByVisibleText(CampoMotivo);
}
public void preencherCampoSubmotivo(String CampoSubMotivo) throws Exception {
}
}
Class FaturamentoGeConectividadeFacilidadesTest
public class FaturamentoGeConectividadeFacilidadesTest {
static WebDriver driver;
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
driver = nav.iniciarNavegador("chrome", "http://10.5.9.45/BkoMais_Selenium/");
}
#Test
public void selecionarFacilidades() throws Exception {
// Logando na aplicação
LogarBkoMaisPage login = new LogarBkoMaisPage(driver);
login.logar("844502", "Bcc201707");
// BackOffice >> FaturamentoGe >> Conectividade
FaturamentoGeConectividadeFacilidadesPage menu = new FaturamentoGeConectividadeFacilidadesPage(driver);
menu.logarFaturamentoGeConectividade();
//Registro >> Novo caso
RegistroNovoCasoPage reg = new RegistroNovoCasoPage(driver);
reg.registrarCaso();
//Preencher campos
FaturamentoGeTratamentoOsPage campo = new FaturamentoGeTratamentoOsPage(driver);
campo.preencherCampoMotivo(" Concluido ");
}
#After
public void tearDown() throws Exception {
Thread.sleep(5000);
driver.quit();
}
}
You need to add pagefactory.init to initialize webelement.
public FaturamentoGeTratamentoOsPage(WebDriver driver) { this.driver = driver;
PageFactory.initElements(driver, this);
}
No use of below line .. because CBOMotive directly returns you a webelement only
WebElement campoMotivo = driver.findElement(By.id(CBOMotivo));
You are getting the error because By.id() expects a String, not a WebElement. You have defined CBOMotivo as a WebElement but are treating it like a String.
The following is correct usage
WebElement campoMotivo = driver.findElement(By.id("cboMotivo"));
What you want is
public void preencherCampoMotivo(String CampoMotivo) {
// Campo Motivo
Select slcMotivo = new Select(CBOMotivo);
slcMotivo.selectByVisibleText(CampoMotivo);
}
I am getting "java.lang.NullPointerException" when I am trying to execute my test case based on POM.
The class BrowserFactory lets me choose a browser, the class Flipkart_Login based on POM stores all the element of that particular page and has a method for Valid_Login()
and finally Test_Flipkart_Login class - calls the Valid_Login() method for executon but when I try to execute this class, I get java.lang.NullPointerException.
Kindly advise!
FAILED: Flipkart_Login_Test
java.lang.NullPointerException
at DataProviders.ConfigDataProvider.getURL(ConfigDataProvider.java:31)
at TestCases.Test_Flipkart_Login.Flipkart_Login_Test(Test_Flipkart_Login.java:19)
public class ConfigDataProvider
{
static Properties pro;
public ConfigDataProvider()
{
File src = new File("C:\\Data\\Bimlesh\\Flipkart_HybridFramework\\Flipkart.Hybrid.FrameworkComplete\\Configuration\\Config.Properties");
try
{
FileInputStream fis = new FileInputStream(src);
pro = new Properties();
pro.load(fis);
} catch (Exception e)
{
System.out.println("The Config exception is :"+e.getMessage());
}
}
public static String getURL()
{
String URL = pro.getProperty("URL");
return URL;
}
public static String ChromePath()
{
String Chrome = pro.getProperty("Chromepath");
return Chrome;
}
public static String IEPath()
{
String IE = pro.getProperty("IEpath");
return IE;
}
}
public class BrowserFactory
{
static WebDriver driver;
public static WebDriver getBrowser(String BrowserName)
{
if(BrowserName.equalsIgnoreCase("Firefox"))
{
driver = new FirefoxDriver();
}
else if(BrowserName.equalsIgnoreCase("Chrome"))
{
System.setProperty("webdriver.chrome.driver", ConfigDataProvider.ChromePath());
driver = new ChromeDriver();
}
else if(BrowserName.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver", ConfigDataProvider.IEPath());
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
return driver;
}
public void ShutDown(WebDriver driver)
{
driver.quit();
}
}
public class Flipkart_Login
{
WebDriver driver;
public Flipkart_Login(WebDriver driver)
{
this.driver=driver;
}
#FindBy(xpath="//a[text()='Log In']") WebElement Login_Click;
#FindBy(xpath="//input[#class='_2zrpKA' and #type='text']") WebElement Enter_Email;
#FindBy(xpath="//input[#class='_2zrpKA _3v41xv' and #type='password']") WebElement Enter_Pass;
#FindBy(xpath="//button[#type='submit' and #class='_3zLR9i _1LctnI _36SmAs']") WebElement Login_Button;
public void Valid_Login()
{
Login_Click.click();
Enter_Email.sendKeys("xxx#gmail.com");
Enter_Pass.sendKeys("xxx");
Login_Button.click();
}
}
public class Test_Flipkart_Login
{
WebDriver driver;
#Test
public void Flipkart_Login_Test()
{
driver = BrowserFactory.getBrowser("Firefox");
driver.get(ConfigDataProvider.getURL());
Flipkart_Login page1 = PageFactory.initElements(driver, Flipkart_Login.class);
page1.Valid_Login();
}
}
You have initialized Properties pro in the constructor of the COnfigDataProider but you are using a static call to getURL method from your test class. Thus pro will be null and not initialized. Remove static call and use the constructor or make pro to static and initialize in static block.
While automating cross browser test, I used the driver in both main and sub method. It is showing syntax error in the line "System.setProperty("webdriver.chrome.driver","D:\chromedriver_win32"
Thanks
import org.openqa.selenium.chrome.ChromeDriver;
public class MyClass {
System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");
static WebDriver driver = new ChromeDriver();
public static void main(String[] args) throws IO Exception {
driver.findElement(By.id("aaa")).clear();
-do-
String B = new MyClass().gettext("eeee");
}
driver.quit();
}
public String getIframe(String id) {
driver.findElement(By.id("ddd")).clear();
-do-
return A;
}
}
I resolved it by modifying the code as below:
import org.openqa.selenium.chrome.ChromeDriver;
public class MyClass {
static Webdriver driver;
public static void main(String[] args) throws IO Exception {
System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.findElement(By.id("aaa")).clear();
-do-
String B = new MyClass().gettext("eeee");
}
driver.quit();
}
public String getIframe(String id) {
driver.findElement(By.id("ddd")).clear();
-do-
return A;
}
}
So Simple!!!