How to Upload a file into web browser using Winium? - java

I know I can upload file to browser with many ways such as: AutoIt, Robot Class, and other ways(I tried them all and they worked most of time).
I got introduced to Winium and I would like to make the same test case with it, that is, upload a file to a browser using it, but I did not know what to do to switch between web driver to winium driver. Please help because I searched a lot for this trick but could not find any result
package testUtilities;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.winium.WiniumDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class WiniumWeb
{
WebDriver driver;
#BeforeClass
public void setUp() throws IOException
{
driver = new FirefoxDriver();
driver.navigate().to("http://the-internet.herokuapp.com/upload");
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\Resources\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists())
{
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try
{
driver = new WiniumDriver(new URL("http://localhost:9999"), null);
} catch (MalformedURLException e)
{
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException
{
String file = System.getProperty("user.dir") + "\\Resources\\TestData.csv";
WebElement window = driver.findElement(By.className("File Upload"));
window.findElement(By.className("#32770")).sendKeys(file);
Thread.sleep(2000);
}
}

if you are still finding solution.I am sharing my script which worked for me.
public class FileUpload extends BaseClass {
static WiniumDriver d;
#BeforeClass
public void setUp() throws IOException {
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
LaunchLocalBrowser("chrome","http://the-internet.herokuapp.com/upload");//use your own code to launch browser
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\lib\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try {
d = new WiniumDriver(new URL("http://localhost:9999"),options);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException {
String file = System.getProperty("user.dir") + "\\lib\\Testdata.txt";
d.findElementByName("File name:").sendKeys(file);
d.findElementByXPath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']").click();
driver.findElement(By.id("file-submit")).click();
}
}

File upload using WiniumDriverService by referring to port- 9999. Creating winium instance using free port having issues. Below code is intended for sample implementation of Browser factory to facilitate web and desktop instances.
public class FactoryManager {
public static ClientFactory getIndividualProduct(EnumProductLists product) {
ClientFactory factory = null;
if (null != product) {
switch (product) {
case CHROME:
factory = new ProductChromeClient();
break;
case DESKTOP:
factory = new ProductWiniumClient();
break;
default:
break;
}
}
return factory;
}
}
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
public class ProductWiniumClient extends ClientFactory {
private WiniumDriverService service;
#Override
protected void startService() {
if (null == service) {
service = new WiniumDriverService.Builder()
.usingDriverExecutable(
new File(System.getProperty("user.dir") + "/WiniumFolder/Winium.Desktop.Driver.exe"))
.usingPort(9999).withVerbose(true).buildDesktopService();
try {
service.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void createService() {
startService();
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
deskClient = new WiniumDriver(service, options);
}
#Override
protected void stopService() {
if (null != service && service.isRunning()) {
service.stop();
}
}
}
public class TestCase1 {
WebDriver webClient;
WiniumDriver deskClient;
ClientFactory lists;
#BeforeTest
public void beforeTest() {
lists = FactoryManager.getIndividualProduct(EnumProductLists.CHROME);
webClient = (WebDriver) this.lists.getClient(WebDriver.class.getTypeName());
lists = FactoryManager.getIndividualProduct(EnumProductLists.DESKTOP);
deskClient = (WiniumDriver) this.lists.getClient("");
}
#Test
public void f() {
if (null != webClient) {
try {
webClient.manage().window().maximize();
webClient.get("https://uploadfiles.io/");
webClient.findElement(By.id("upload-window")).click();
String file = System.getProperty("user.dir") + "\\files\\upload.txt";
deskClient.findElement(By.name("File name:")).sendKeys(file);
deskClient.findElement(By.xpath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']")).click();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Client Instance is Null!");
}
}
#AfterTest
public void afterTest() {
}
}

Related

Unable to open browser in selenium, throws a "null" message

I have a framework that uses POM model and I have used a Utils folder structure which has DriverFactory,Constant and ReadConfigFile java files that configures and opens the browser. (code below)
Now before I did this (introducing the Utils package) the code was running fine and after introducing the Utils package i am getting "Unable to load browsernull" exception.
Not sure what is causing the problem. I am using a Mac machine.
Constant.java file:
package Utils;
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties/config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir")+"CucumberFramework/src/test/java/Resources/geckodriver";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir")+"CucumberFramework/src/test/java/Resources/chromedriver";
}
DriverFactory.java file:
package Utils;
//import com.sun.java.util.jar.pack.Instruction;
import com.sun.tools.javac.code.Attribute;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import pageObjects.AddIssuePage;
import pageObjects.Login_Page;
import java.util.concurrent.TimeUnit;
public class DriverFactory {
public static WebDriver driver;
public static Login_Page login_page;
public static AddIssuePage addIssuePage;
public WebDriver getDriver() {
try
{
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (null == driver) {
System.setProperty("webdriver.geckodriver", Constant.GECKO_DRIVER_DIRECTORY);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver();
}
break;
case "chrome":
if (null == driver) {
System.setProperty("webdriver.chromedriver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
}
break;
}
} catch (Exception e)
{
System.out.println("Unable to load browser" + e.getMessage());
} finally
{
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
login_page = PageFactory.initElements(driver, Login_Page.class);
}
return driver;
}
}
ReadConfigFile.java file:
package Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile () {
try {
ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
}
Stacktrace:
java.lang.NullPointerException
at Utils.DriverFactory.getDriver(DriverFactory.java:63)
at Steps.MasterHooks.setup(MasterHooks.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at cucumber.runtime.Utils$1.call(Utils.java:40)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:34)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
java.lang.NullPointerException
at Utils.DriverFactory.getDriver(DriverFactory.java:63)
at Steps.MasterHooks.setup(MasterHooks.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at cucumber.runtime.Utils$1.call(Utils.java:40)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:34)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Process finished with exit code 1
MasterHooks
package Steps;
import Utils.DriverFactory;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class MasterHooks extends DriverFactory {
#Before
public void setup() {
driver = getDriver();
}
#After
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
This error message...
Unable to load browsernull
...implies that the function getBrowser() is returning null.
I would suggest the changes:
In ReadConfigFile.java:
Change:
ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
To:
File src = new File(Constant.CONFIG_PROPERTIES_DIRECTORY);
FileInputStream fis = new FileInputStream(src);
Properties prop = new Properties();
prop.load(fis);
Change:
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
To:
public String getBrowser(){
return prop.getProperty("browser");
}
In Constant.java
Change:
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties/config.properties";
To:
public final static String CONFIG_PROPERTIES_DIRECTORY = "./src/main/java/properties/config.properties";
In DriverFactory.java
Change:
"webdriver.geckodriver"
To:
"webdriver.gecko.driver"
Change:
"webdriver.chromedriver"
To:
"webdriver.chrome.driver"
The problem here is that, input instance variable of type Input Stream is assigned to null in Read config file class.
It should be assigned to input stream as given below.
package Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile () {
try {
input = ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
}
Could you share your properties/config.properties file?
From the infos you shared I was thinking about that:
When, in DriverFactory, you call
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
In the getBrowser() there is:
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
So, if prop.getProperty("browser") is null, you are returning " " in browserName.
In the switch:
switch (browserName) {
case "firefox":
if (null == driver) {
System.setProperty("webdriver.geckodriver", Constant.GECKO_DRIVER_DIRECTORY);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver();
}
break;
case "chrome":
if (null == driver) {
System.setProperty("webdriver.chromedriver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
}
break;
}
} catch (Exception e)
{
System.out.println("Unable to load browser" + e.getMessage());
} finally
{
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
login_page = PageFactory.initElements(driver, Login_Page.class);
}
I don't see any check in the case browserName is " " or in another case (I mean, there isn't a default case). So, in case browserName is " " or something else different of "firefox" or "chrome" you go directly to the finally statement (the finally is always executed). In this case, because the driver is not instantiated, you will have a nullpointer exception in:
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);

Selenium TestNG- created config properties and read properties file, now I need to call it in my test case

I created a Properties File and config.properities file in selenium. Now I need to call these properties in my test case. I am stuck on how the code should look like to call this on my test case.
PropertiesFile
package config;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesFile {
public static void main(String[] args){
readPropertiesFile();
}
public static void readPropertiesFile(){
Properties prop = new Properties();
try {
InputStream input = new
FileInputStream("C:\\Users\\chetan.patel\\git\\uvavoices-
automation\\config.properties");
prop.load(input);
System.out.println(prop.getProperty("url"));
System.out.println(prop.getProperty("username"));
System.out.println(prop.getProperty("password"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my test case:
public class AcceptanceTest {
public WebDriver driver;
public String baseURL;
private static final Logger log =
LogManager.getLogger(AcceptanceTest.class.getName());
ExtentReports report;
ExtentTest test;
WaitTypes wt;
LoginPageFactory login;
VoicesPageFactory voices;
SoftAssert sa;
#BeforeSuite
public void beforeSuite(){
report = new
ExtentReports(System.getProperty("user.dir")+"/Reports/AcceptanceTest.html",
true);
test = report.startTest("Acceptance test");
}
#BeforeMethod
public void beforeMethod() {
PropertiesFile data = new PropertiesFile();
driver = new FirefoxDriver();
wt = new WaitTypes(driver);
login = new LoginPageFactory(driver);
voices = new VoicesPageFactory(driver);
sa = new SoftAssert();
//Starting the Web Browser and navigating to the UVA Voices development
environment
data.readPropertiesFile();
baseURL = "url";
test.log(LogStatus.INFO, "Browser Started");
log.info("Browser started");
driver.manage().window().maximize();
driver.get(baseURL);
}
#Test
public void VerifyingBubbles() throws InterruptedException {
//User Login and Password
login.username("chetan.patel");
test.log(LogStatus.INFO, "Entered Username");
you can try the following way,
package config;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesFile {
public static void main(String[] args){
// readPropertiesFile();
}
private java.util.Properties prop=null;
public void readPropertiesFile(){
prop = new Properties();
try {
InputStream input = new
FileInputStream("C:\\Users\\chetan.patel\\git\\uvavoices-
automation\\config.properties");
prop.load(input);
System.out.println(prop.getProperty("url"));
System.out.println(prop.getProperty("username"));
System.out.println(prop.getProperty("password"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getPropertyValue(String key){
return prop.getProperty(key);
}
}
And To get base URL in before method as follows,
#BeforeMethod
public void beforeMethod() {
PropertiesFile data = new PropertiesFile();
driver = new FirefoxDriver();
wt = new WaitTypes(driver);
login = new LoginPageFactory(driver);
voices = new VoicesPageFactory(driver);
sa = new SoftAssert();
//Starting the Web Browser and navigating to the UVA Voices development environment
data.readPropertiesFile();
String baseURL = data.getPropertyValue("url");
test.log(LogStatus.INFO, "Browser Started");
log.info("Browser started");
driver.manage().window().maximize();
driver.get(baseURL);
}

Orientdb: Import database in memory and use it as graph

This is my Java DB class in which I open database and import database export file in memory graph database, where I define all database schema information for testing cases.
Operation going well but how can I access the imported database as graph instance and not document instance of database?
I try so many things but I have failed...
Error :
The Person class exist in my schema so something else is going wrong.
Caused by:
> com.orientechnologies.orient.core.exception.OCommandExecutionException:
> Class 'PERSON' was not found in current database
Code:
import com.orientechnologies.orient.core.db.tool.ODatabaseExportException;
import com.orientechnologies.orient.core.db.tool.ODatabaseImport;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import lombok.Getter;
import java.io.IOException;
public class Db {
#Getter private static OrientGraphFactory factory;
#Getter private static OrientGraphNoTx graph;
static public void main(String[] args){
open("memory","database");
importDB("/schemas/diary-11202016.gz");
try {
seed();
} catch (InterruptedException e) {
e.printStackTrace();
}
closeDB();
}
public static void open(String dbType, String dbUrl) {
String dbInfo = dbType + ":" + dbUrl;
System.out.println(dbInfo);
factory = new OrientGraphFactory(dbInfo, "root", "root").setupPool(1, 10);
graph = factory.getNoTx();
}
public static void importDB(String path) {
try {
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), Db.class.getResourceAsStream(path), (iText) -> {
System.out.print(iText);
});
importDb.setMerge(true);
importDb.importDatabase();
importDb.close();
System.out.println("\nImporting database: OK");
} catch (ODatabaseExportException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void seed() throws InterruptedException {
System.out.println("Starting to seed...");
for (Vertex v : (Iterable<Vertex>) graph.command( new OCommandSQL("select from Person")).execute()) {
System.out.println("- Bought: " + v.getProperty("name"));
}
System.out.println("Finish to seed...");
}
public static void closeDB() {
factory.close();
}
}
Replace the following piece of code
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), Db.class.getResourceAsStream(path), (iText) -> {
System.out.print(iText);
});
importDb.setMerge(true);
with
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), path, (iText) -> {
System.out.print(iText);
});
// importDb.setMerge(true);

Selenium WebDriver NullPointerException while grabbing url

I have found multiple answers to this issue but none that seem to help me here. When ever i run my test, I get a NullPointerException. I image it is a simple fix but I can't find it.
Here is my set up class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
public class TestSetUp {
private WebDriver driver;
protected StringBuffer verificationErrors = new StringBuffer();
public WebDriver getDriver() {
return driver;
}
private void setDriver(String type, String url) {
switch (type) {
case Config.FIREFOX_DRIVER:
System.out.println("Setting drivers for Firefox...");
driver = initFireFoxDriver(url);
break;
default:
System.out.print("invalid browser type");
}
}
private static WebDriver initFireFoxDriver(String url) {
System.out.println("Launching Firefox browser...");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to(url);
return driver;
}
#BeforeClass
#Parameters({"type","url"})
public void initializeTestBaseSetup(String type, String url) {
try {
setDriver(type, url);
} catch (Exception e) {
System.out.println("Error....." + Arrays.toString(e.getStackTrace()));
}
}
#AfterClass
public void tearDown() {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}
This is my LoginPage class where the error is being thrown:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LoginPage {
private WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
private String getLoginTitle() {
return driver.getTitle();
}
public boolean verifyURL() {
return driver.getCurrentUrl().contains("login");
}
public boolean verifyLoginTitle() {
return getLoginTitle().contains(Config.TITLE + " - Log In");
}
public boolean verifySignInError() {
enterUsername("test");
enterPassword("pass");
clickLogin();
return getErrorMessage().contains("Incorrect Username or Password");
}
public boolean verifyForgotPassword() {
return driver.findElement(Config.FORGOT_PASS_NODE).isDisplayed();
}
public boolean verifyLicencing() {
Config.changeSetting("multi_license", 1, driver);
return driver.findElement(Config.LIC_KEY_NODE).isDisplayed();
}
public boolean verifyCreateAccount() {
Config.changeSetting("user_reg", 0, driver);
if(driver.findElement(Config.CREATE_ACCOUNT_NODE).isDisplayed()) {
return false;
}
else {
Config.changeSetting("user_reg", 1, driver);
}
return driver.findElement(Config.CREATE_ACCOUNT_NODE).isDisplayed();
}
public HomePage signIn(String username, String password) {
enterUsername(username);
enterPassword(password);
clickLogin();
return new HomePage(driver);
}
public void enterUsername(String username) {
WebElement identity = driver.findElement(Config.IDENTITY_NODE);
if(identity.isDisplayed())
identity.sendKeys(username);
}
public void enterPassword(String password) {
WebElement pass = driver.findElement(Config.CREDENTIAL_NODE);
if(pass.isDisplayed())
pass.sendKeys(password);
}
public void clickLogin() {
WebElement loginBtn = driver.findElement(Config.SUBMIT_NODE);
if(loginBtn.isDisplayed())
loginBtn.click();
}
public String getErrorMessage() {
String errorMessage = null;
WebElement errorMsg = driver.findElement(Config.DANGER_NODE);
if(errorMsg.isDisplayed())
errorMessage = errorMsg.getText();
return errorMessage;
}
}
And finally my test case:
import org.junit.Assert;
import org.junit.Before;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
public class LoginPageTest extends TestSetUp {
private WebDriver driver;
#Before
public void setUp() {
driver = getDriver();
}
#Test
public void verifyLoginInFunction() {
System.out.println("Log In functionality being tested...");
LoginPage loginPage = new LoginPage(driver);
try {
Assert.assertTrue("The url is incorrect", loginPage.verifyURL());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("Title did not match", loginPage.verifyLoginTitle());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("Error message did not match", loginPage.verifySignInError());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("\'Forgot Password?\' link is missing", loginPage.verifyForgotPassword());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("Create Account setting not working", loginPage.verifyCreateAccount());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("Additional Licence Key setting not working", loginPage.verifyLicencing());
} catch (Error e) {
verificationErrors.append(e.toString());
}
HomePage homePage = loginPage.signIn(Config.STUDENT, Config.STUDENTPASS);
try {
Assert.assertTrue("Login did not work", homePage.verifyURL());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
}
I have been trying and just do not know what is causing the issue.
So, I was just dealing with this same problem and realized this question was asked about 7 years ago. I thought I would share what I have come up with as my solution.
For the instance you are trying to access you are passing a null. You assign a value to something that hasn't been initialized yet which gives you the exception you are seeing :) a null value into the driver loginPage is a no no. First initialize -> then pass value -> happy outputs.
I'm not here to give you a coding lesson as you have proven to show you know what you are doing, but happy coding!

Selenium working in netbeans but not when converting the project to exe

Hi,
I'm trying to link selenium with my exe version of the java project so that selenium will be executed when clicking a button.
Selenium code is:
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.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Pay {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
String Enum;
String cpr;
public Pay(String nEnum){
Enum = nEnum;
this.cpr = "000";
}
public Pay(String nEnum, String nCpr){
Enum = nEnum;
this.cpr = nCpr;
}
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "A:\\Documents\\NetBeansProjects\\Electricity\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
baseUrl = "http://www.bahrain.bh/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public void testRent() throws Exception {
driver.get(baseUrl + "/wps/portal/!ut/p/c5/04_SB8K8xLLM9MSSzPy8xBz9CP0os3gLAxNHQ093A3d_J29DA08_cw9TT1dvI8cgU_1wkA6zeGd3Rw8Tcx8DAwsXNwsDIydTM89AAxcDA09TiLwBDuBooO_nkZ-bqh-cmqdfkJ2d5uioqAgARs8Bqw!!/dl3/d3/L0lHSkovd0RNQU5rQUVnQSEhL1lCZncvYXI!/");
driver.findElement(By.cssSelector("a.toolbarLink > div")).click();
driver.findElement(By.xpath("//form[#id='viewns_7_804A1IG0GOBK10IN7H5IEK2AV1_:eServicesForm']/div/table/tbody/tr[7]/td[2]/table/tbody/tr/td[2]/a/span")).click();
driver.findElement(By.cssSelector("img[alt=\"Launch Service\"]")).click();
new Select(driver.findElement(By.id("viewns_7_OAHIGGG0GGV880I1V3LJ6130G3_:PayerLoginForm:mewIdType"))).selectByVisibleText("CPR");
driver.findElement(By.id("viewns_7_OAHIGGG0GGV880I1V3LJ6130G3_:PayerLoginForm:mewId")).clear();
driver.findElement(By.id("viewns_7_OAHIGGG0GGV880I1V3LJ6130G3_:PayerLoginForm:mewId")).sendKeys(cpr);
driver.findElement(By.id("viewns_7_OAHIGGG0GGV880I1V3LJ6130G3_:PayerLoginForm:mewAccountNo")).clear();
driver.findElement(By.id("viewns_7_OAHIGGG0GGV880I1V3LJ6130G3_:PayerLoginForm:mewAccountNo")).sendKeys(Enum);
driver.findElement(By.name("viewns_7_OAHIGGG0GGV880I1V3LJ6130G3_:PayerLoginForm:_id4")).click();
driver.findElement(By.cssSelector("input[type=\"checkbox\"]")).click();
driver.findElement(By.name("viewns_7_OAHIGGG0GGV880I1V3LJ6130G3_:_id0:_id1")).click();
driver.findElement(By.id("Debit Card")).click();
driver.findElement(By.xpath("//tr[7]/td[2]/span/label")).click();
driver.findElement(By.name("btnPay2")).click();
driver.findElement(By.name("Ecom_Payment_Card_Name")).clear();
driver.findElement(By.name("Ecom_Payment_Card_Name")).sendKeys("AAA");
driver.findElement(By.name("Ecom_Payment_Card_Number")).clear();
driver.findElement(By.name("Ecom_Payment_Card_Number")).sendKeys("123");
}
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;
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Home
*/
I will call this class and pass it the needed information and execute the selenium code by calling the methods.
My code works perfectly when executed in netbeans however when convert it to exe file, I can't run selenium anymore.
The code of the other class which will run selenium methods:
String eNum = "123";
Pay p1 = new Pay(eNum);
try {
p1.setUp();
} catch (Exception ex) {
Logger.getLogger(Building1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
p1.testRent();
} catch (Exception ex) {
Logger.getLogger(Building1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
p1.tearDown();
} catch (Exception ex) {
Logger.getLogger(Building1.class.getName()).log(Level.SEVERE, null, ex);
}
Thank you...

Categories