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);
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Here, I am using page object model and I want to pass the driver to other classes.But i am getting null pointer exception while launch the website (driver.get("")).
This is my base class
public class BaseClass {
public WebDriver driver;
public Logger logger = Logger.getLogger(Common.class.getPackage().getName());
public void startBrowser() {
if(driver == null) {
System.setProperty("webdriver.chrome.driver", "desktop/chromedriver.exe");
driver = new ChromeDriver();
}
}
public void quitBrowser() {
driver.quit();
}
}
and then this is my runner class:
public class TestRunnerTestNG extends AbstractTestNGCucumberTests {
BaseClass a;
#BeforeClass
public void launch()
{
a = new BaseClass();
a.startBrowser();
}
#AfterClass
public void tearBrowser()
{
a.quitBrowser();
}
}
Here, I am starting the browser using Beforeclass annotation and quit the browser using afterClass annotation.
and the following class is my page Object class: and here I have the method for launch the url:
public class SignIn extends BaseClass {
public SignIn(WebDriver driver) {
this.driver = driver ;
PageFactory.initElements(driver, this);
}
//Locators
#FindBy(id = "email")
private WebElement user_Email;
#FindBy(id = "password")
private WebElement user_Password;
#FindBy(xpath = "//span[text()='Sign In']")
private WebElement signIn_Btn;
public void landing()
{
driver.get("https://***************"); <<<< Here I am getting the null pointer exception.
}
public void signInPageGUI()
{
boolean checkSignInTextGUI = waitElement(signInText);
Assert.assertTrue(checkSignInTextGUI);
boolean CheckEmailField = waitElement(user_Email);
Assert.assertTrue(CheckEmailField);
boolean checkPwdField = waitElement(user_Password);
Assert.assertTrue(checkPwdField);
}
private void emailField(String emailName) {
user_Email.sendKeys(emailName);
}
private void passwordField(String password) {
user_Password.sendKeys(password);
}
}
and the final code is my step definition class and this is place I am calling the code.
public class LoginPage {
WebDriver driver ;
#Given("user landed to the yoco URL {string}")
public void landedOnYoCo(String string) {
System.out.println("print the string" +string);
System.out.println("driver value is " );
SignIn logIN = new SignIn(driver);
logIN.landing();
}
}
Here, Only I am calling the landing method to launch the website.
and The error is:
java.lang.NullPointerException
at pageObject.SignIn.landing(SignIn.java:83)
at stepDefs.LoginPage.landedOnYoCo(LoginPage.java:32)
at ✽.user landed to the yoco URL "https://my.yocoboard.com"(file:///Users/vinoth/Git/YoCoAutomation/src/test/resources/logIN.feature:7)
Call startBrowser before calling landing to initialize driver.
public void landedOnYoCo(String string) {
System.out.println("print the string" +string);
System.out.println("driver value is " );
SignIn logIN = new SignIn(driver);
logIN.startBrowser();
logIN.landing();
}
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);
}
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/");
}
My coding not find element. Pls anyone help me to come out of my mistake.
Testcase
#Test
public void main() throws Exception {
Thread.sleep(5000);
System.out.println("Before sign in action execution");
SignIn_Action.Execute(iTestCaseRow);
}
SignIn_Action
public class SignIn_Action{
public static void Execute(int iTestCaseRow) throws Exception{
// Fetch user name from Excel
String sUserName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_UserName);
System.out.println("User Name read from --> "+ sUserName);
// Fetch password from Excel
String sPassword = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Password);
System.out.println("Password read from excel --> "+ sPassword);
LoginPageObjects.txtbx_username().sendKeys(sUserName);
LoginPageObjects.txtbx_password().sendKeys(sPassword);
LoginPageObjects.btn_login().click();
}
LoginPageObject class
public class LoginPageObjects extends BaseClass {
private static WebElement element = null;
public LoginPageObjects(WebDriver driver){
super(driver);
}
public static WebElement txtbx_username(){
try {
WebElement element = null;
System.out.println("Inside txtbx_username method");
element = driver.findElement(By.name("first_name"));
System.out.println("Fetched element name is : "+element);
Log.info("Username text box found");
}catch (Exception e){
Log.error("UserName text box is not found on the Login Page");
throw(e);
}
return element;
}
}
}
BaseClass
public class BaseClass {
public static WebDriver driver;
public static boolean bResult;
public BaseClass(WebDriver driver){
BaseClass.driver = driver;
BaseClass.bResult = true;
}
}
My problem is in the below code
element = driver.findElement(By.name("first_name"));
This code is not find element and it shows below error message
java.lang.NullPointerException
at pageObjects.LoginPageObjects.txtbx_username(LoginPageObjects.java:27)
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.