How can I setup Fluentlenium to run in different browser drivers? - selenium

I am trying to run Fluentlenium in different browser drivers. I think I need to configure the getDefaultDriver() from Fluentlenium but I am not exactly sure on how to do that. Any exmaple codes would be great. Here is my code and it's not working. The message I am getting in Eclipse is:
"java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
at com.google.common.base.Preconditions.checkState(Preconditions.java:176)
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:105)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:75)
at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:107)
at com.picklist.tests.PicklistCreate.(PicklistCreate.java:32)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:195)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:244)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:241)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
"
My Code below:
public WebDriver driver = new ChromeDriver();
// Overrides the default driver
#Override
public WebDriver getDefaultDriver() {
System.setProperty("webdriver.chrome.driver", "C:/chromeDriver/chromedriver.exe"); // Set for ChromeDriver
//return driver;
return driver;
}
If I do the following code, it works but then the driver is no longer defined and I got a ton od code that uses driver.xxx:
// Overrides the default driver
#Override
public WebDriver getDefaultDriver() {
return new ChromeDriver();
}

Here is how I solved this:
public WebDriver driver;
// Overrides the default driver
#Override
public WebDriver getDefaultDriver() {
System.setProperty("webdriver.chrome.driver", "C:/chromeDriver/chromedriver.exe"); // Set for ChromeDriver
driver = new ChromeDriver();
return driver;
}

There is not getDefaultDriver in FluentTest, you can use this code:
#Override
public WebDriver newWebDriver() {
System.setProperty("webdriver.chrome.driver", "path-to-chrome-driver/chromedriver");
Map<String, Object> chromeOptions = new HashMap<String, Object>();
chromeOptions.put("binary", "/usr/bin/chromium-browser");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
return new ChromeDriver(capabilities);
}

Have an abstract createDriver() function that is overridden by each type of driver. Each driver should return a correctly configured driver, which is then stored, and returned when you call getDefaultDriver();

Related

Is InvalidArgumentException ensureCleanSession a known IEDriverServer 3.12.0 issue or am I instantiating it incorrectly?

When I attempt to instantiate IEDriverServer 3.12.0 like this:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class StartInternetExplorer {
public static void main(String[] args) {
// Add to Windows PATH variable: C:\IEDriverServer_Win32_3.12.0\;
String executable = "C:\\IEDriverServer_Win32_3.12.0\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", executable);
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.google.com");
driver.quit();
}
}
I see this exception stack trace:
Started InternetExplorerDriver server (32-bit)
3.12.0.0
Listening on port 46039
Only local connections are allowed
Exception in thread "main" org.openqa.selenium.InvalidArgumentException: All firstMatch elements failed validation
Invalid capabilities in firstMatch element 0: unknown capability named ensureCleanSession
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T14:04:26.12Z'
System info: host: 'XXXXXXXX', ip: '127.0.0.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_161'
Driver info: driver.version: InternetExplorerDriver
remote stacktrace:
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:123)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:126)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:545)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:209)
at org.openqa.selenium.ie.InternetExplorerDriver.run(InternetExplorerDriver.java:223)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:215)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:152)
at app.StartInternetExplorer.main(StartInternetExplorer.java:11)
I don't know where the "ensureCleanSession" argument is coming from, so I don't know if this means there is a bug in 3.12.0 or if I am not instantiating IEDriverServer properly.
Tried passing 4 slashes in URL and it worked. Seems they have make some changes in selenium API but I am not sure. This worked for me:
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Money {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
InternetExplorerDriver driver=new InternetExplorerDriver();
driver.get("https:\\\\www.google.com");
}
}
I cannot replicate this in release 3.14.0 - The solution was to wait for a new release.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class StartInternetExplorer {
public static void main(String[] args) {
// Add to Windows PATH variable: C:\IEDriverServer_Win32_3.14.0\;
String executable = "C:\\IEDriverServer_Win32_3.14.0\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", executable);
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.google.com");
driver.quit();
}
}

org.openqa.selenium.SessionNotCreatedException: Unable to find a matching set of capabilities while initiating Firefox v37 through Selenium v3.11.0

I am trying to run test a run a website in Firefox, but I am getting error "The path to the driver executable must be set by the webdriver.gecko.driver system property;" I have set the path correctly, still don't know where the problem is. Here is my code:
if (browsers.equalsIgnoreCase("Firefox"))
{
String driverPath = System.getProperty("user.dir") + "\\src/test/java\\drivers\\geckodriver.exe";
System.setProperty("webdriver.firefox.marionette", "false");
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} else if (browsers.equalsIgnoreCase("Chrome")) {
// String driverPath = System.getProperty("user.dir") +
// "\\src\\Drivers\\chromedriver";
// System.setProperty("webdriver.chrome.driver", driverPath);
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
Here is the Failure Trace of my code:
FAILED CONFIGURATION: #BeforeClass launchBrowser
org.openqa.selenium.SessionNotCreatedException: Unable to find a matching set of capabilities
Build info: version: '3.8.0', revision: '924c4067df', time: '2017-11-30T11:36:59.109Z'
System info: host: 'DSCHD-PC-180', ip: '192.168.6.122', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_161'
Driver info: driver.version: FirefoxDriver
remote stacktrace:
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:123)
org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:126)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
at Utility.UtilityMethods.openBrowser(UtilityMethods.java:26)
at TestCases.LoginTestCase.launchBrowser(LoginTestCase.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:455)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:168)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
SKIPPED CONFIGURATION: #AfterClass quitBrowser
SKIPPED: registration
To keep things simple, as you are using Selenium Client v3.11.0 and Firefox v37 you need to download the latest GeckoDriver from mozilla/geckodriver and save it any where within your system. Next within the System.setProperty() line pass the Key webdriver.gecko.driver along with the Value as the absolute path of the GeckoDriver and finally through DesiredCapabilities class set the capability marionatte to false and merge into an instance of FirefoxOptions instance to initiate the Firefox browser as follows :
System.setProperty("webdriver.gecko.driver", "C:/path/to/geckodriver.exe");
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability("marionatte", false);
FirefoxOptions opt = new FirefoxOptions();
opt.merge(dc);
FirefoxDriver driver = new FirefoxDriver(opt);
driver.get("https://stackoverflow.com");
System.out.println("Application opened");
System.out.println("Page Title is : "+driver.getTitle());
driver.quit();
Update
As per your comment update you are using GeckoDriver v0.20.1.
But if you look back at the Release Notes of GeckoDriver v0.18.0 it clearly mentions :
geckodriver now recommends Firefox 53 and greater
So using GeckoDriver v0.18.0 and above you have to mandatory use Firefox 53 and greater. To get rid of this constraint you can downgrade either to any of these versions :
GeckoDriver v0.17.0
GeckoDriver v0.16.1
This is how system property is set:
System.setProperty("webdriver.gecko.driver", "C:\\...\\geckodriver.exe");
I had this error for 2 days, the solution for me was in Set.Platform, put Platform.ANY or Platform.Windows because Platform.WIN10 not worked, marionette wasn't necessary.
public class Main { public static RemoteWebDriver driver;
public static void main(String[] args) throws MalformedURLException {
System.setProperty("webdriver.gecko.driver", "D:/Lib/geckodriver.exe");
DesiredCapabilities desiredCapabilities = new
DesiredCapabilities().firefox();
desiredCapabilities.setPlatform(Platform.ANY);
desiredCapabilities.setBrowserName("firefox");
driver = new RemoteWebDriver(new URL("http://172.20.19.182:5557/wd/hub"),
desiredCapabilities);
driver.navigate().to("http://www.google.com");
driver.findElementByName("q").sendKeys("execute automation");
driver.findElementByName("q").sendKeys(Keys.ENTER);
driver.close();
// write your code here
}
you are using user.dir that basically means : current working directory
Here is the code that let you initialize firefox browser using selenium.
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\your\\gecko\\driver\\path\\geckodriver.exe");
driver = new firefoxDriver();
That's it ! you can use Firefox driver to performs several operations like :
1. driver.get(String args0);
2. driver.getCurrentUrl();
3. driver.getPageSource();
4. driver.getTitle();
5. driver.findElememt(By args0);
6. driver.findElements(By args0);
7. driver.naviagate();
8. driver.manage();
9. driver.close();
10. driver.quit();
11. driver.switchTo();
12. driver.getWindowHandle();
13. driver.getWindowHandles();
Please let me know if you have any concerns related to this.
Just updated your code. You will have to set driver path while setProperty and user webdriver.gecko.driver for latest firefox driver.
if (browsers.equalsIgnoreCase("Firefox")) {
String driverPath = System.getProperty("user.dir") + "\\src\\test\\java\\drivers\\geckodriver.exe";
System.setProperty("webdriver.firefox.driver", "driverPath");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("marionette", false);
FirefoxOptions options = new FirefoxOptions();
options.merge(capabilities);
FirefoxDriver driver = new FirefoxDriver(options);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
else if (browsers.equalsIgnoreCase("Chrome")) {
// String driverPath = System.getProperty("user.dir") +
// "\\src\\Drivers\\chromedriver";
// System.setProperty("webdriver.chrome.driver", driverPath);
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
Let me know.

Getting org.openqa.selenium.UnsupportedCommandException: mouseMoveTo

I am using selenium 3.5.3 and standalone selenium box.
I am trying to hover an element with following code:
RemoteWebDriver driver = null;
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability("browserName", "firefox");
dc.setCapability("version", "55");
dc.setCapability("auth",GlobalProperties.seleniumboxAuthKey());
try {
driver = new RemoteWebDriver(new
URL("http://myseleniumboxurl.com/wd/hub"), dc);
}
catch (MalformedURLException e) {
System.out.println(e);
}
driver.get("https://github.com/SeleniumHQ");
Actions action = new Actions(driver);
WebElement elem = driver.findElement(By.xpath("//a[contains(#href, '/pricing')]"));
action.moveToElement(elem).perform();
I am getting following exception:
Caused by: org.openqa.selenium.UnsupportedCommandException: mouseMoveTo
at org.openqa.selenium.remote.http.AbstractHttpCommandCodec.encode(AbstractHttpCommandCodec.java:220)
at org.openqa.selenium.remote.http.AbstractHttpCommandCodec.encode(AbstractHttpCommandCodec.java:118)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
at org.openqa.selenium.remote.RemoteExecuteMethod.execute(RemoteExecuteMethod.java:35)
at org.openqa.selenium.remote.RemoteMouse.mouseMove(RemoteMouse.java:89)
at org.openqa.selenium.support.events.internal.EventFiringMouse.mouseMove(EventFiringMouse.java:58)
at org.openqa.selenium.remote.server.handler.interactions.MouseMoveToLocation.call(MouseMoveToLocation.java:59)
at org.openqa.selenium.remote.server.handler.interactions.MouseMoveToLocation.call(MouseMoveToLocation.java:32)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:176)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Any possible workaround or solution please?
In Selenium 3.5.0 mouse move not working properly. So you can use java script libraries and use a java script command to mouse move on element

After executing code inside #BeforeTest its giving null pointer exception for #Test

After executing the#BeforeTest its showing java.lang.NullPointerException for #Test part.
Error displayed:
Starting ChromeDriver 2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) on port 34173
Only local connections are allowed.
Sep 08, 2017 10:40:43 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
FAILED CONFIGURATION: #AfterTest Aftertest
java.lang.NullPointerException
at SampleTesting.Test1.Aftertest(Test1.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:224)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:146)
at org.testng.TestRunner.afterRun(TestRunner.java:958)
at org.testng.TestRunner.run(TestRunner.java:606)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
FAILED: Test1
java.lang.NullPointerException
at SampleTesting.Test1.Test1(Test1.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
Configuration Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
Configuration Failures: 1, Skips: 0
===============================================
Code Used
package SampleTesting;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.*;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.Select;
public class NameClassTest {
WebDriver driver;
ChromeOptions options;
#Test
public void Test1() {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement tabAgreement = driver.findElement(By.xpath("***Value***"));
tabAgreement.click();
WebElement btnNew = driver.findElement(By.xpath("***Value***"));
btnNew.click();
Select lstRecordType = new Select(driver.findElement(By.id***Value***));
lstRecordType.selectByVisibleText("MSA");
WebElement btnContinue = driver.findElement(By.xpath("***Value***"));
btnContinue.click();
WebElement txtAgreementName = driver.findElement(By.xpath("***Value***"));
txtAgreementName.clear();
txtAgreementName.sendKeys("***Value***");
Date date = new Date();
System.out.println("Date is "+ date);
}
#BeforeTest
public void BeforeTest() {
options = new ChromeOptions();
options.addArguments("user-data-dir=C:\\\\Users\\UserName\\AppData\\Local\\Google\\Chrome\\User Data");
String exepath =
"C:\\\\Users\\UserNAme\\Downloads\\chromedriver_win32\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver",exepath);
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("***URL***");
WebElement userName = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
WebElement btnLogin = driver.findElement(By.id("Login"));
userName.sendKeys("****userName****");
password.sendKeys("****password****");
btnLogin.click();
}
#AfterTest
public void Aftertest() {
WebElement drpUserName = driver.findElement(By.id***Value***);
drpUserName.click();
WebElement lnkLogout = driver.findElement(By.xpath(***Value***));
lnkLogout.click();
driver.close();
}
}
TestNG.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite_SuiteName">
<test name="Test_TestName">
<classes>
<class name="SuiteName.ClassName"/>
</classes>
</test> <!-- Test_TestName -->
</suite> <!-- Suite_SuiteName -->
Its executing the block under #BeforeTest successfully but when its coming to #Test part its giving an error message - Null Pointer exception. I am not sure what mistake I made here in my code.
This is because you have mentioned WebDriver driver = new ChromeDriver(options); in #BeforeMethod annotated method. So your webdriver instance limited for that method only.
So if go in #test annotated method it will find driver not initialized so throw the NullPointerException
Just remove WebDriver from here
#BeforeTest
public void BeforeTest()
{
options = new ChromeOptions();
options.addArguments("user-data-dir=C:\\\\Users\\UserName\\AppData\\Local\\Google\\Chrome\\User Data");
String exepath = "C:\\\\Users\\UserNAme\\Downloads\\chromedriver_win32\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver",exepath);
driver = new ChromeDriver(options); // remove "WebDriver" from this line
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("***URL***");
Let me know if still have issue. Thanks :)
In your #BeforeTest annotated method you have this line
WebDriver driver = new ChromeDriver(options);
This causes your code to shadow out the class level data member and so when your #Test methods try accessing the driver, you hit a NullPointerException.
To fix this, please change WebDriver driver = new ChromeDriver(options); to driver = new ChromeDriver(options); in your #BeforeTest annotated method.
On a side note, I would recommend that you either use one of the following instead of using the #BeforeTest because #BeforeTest methods are called only once per <test> tag. So if you have two test classes which are relying on the #BeforeTest method, then you are again looking at NullPointerException
#BeforeClass - so that the webdriver is instantiated once per test class and is then shared by all the #Test methods in the class. The issue would be that you would need to resort to sequential execution only, because parallel execution can cause test methods to step on each other's shoes.
#BeforeMethod - so that the webdriver is instatiated once for every #Test method. This causes a browser to be spun off for every test method. The flip side of this would be that you would need to use ThreadLocal if you want run the methods in parallel. If sequential execution is fine, then you don't need to do anything extra.
Try creating object of WebDriver outside #BeforeTests
as mentioned below,
public class nameClassTest {
WebDriver driver = new ChromeDriver(options);
#BeforeTest
public void BeforeTest()
{
}
that will resolve your issue.

java.lang.NullPointerException error while running test ng case

I am trying to run this code with TestNG but all it gives me is java.lang.NullPointerException error. Firefox does get opened but after that error comes up. What's going wrong. Please help!
Also is it mandatory to run testNG with XML.
public class GuestCheckout
{
public WebDriver driver ;
public String baseURL = "http://www.google.com";
#BeforeTest
public void setBaseURL(){
WebDriver driver = new FirefoxDriver();
driver.get(baseURL);
}
#Test(priority = 0)
public void EmailPasswordEntry() {
// Entering Email and Password values
driver.findElement(By.id("loginRegister")).click();
WebElement email = driver.findElement(By.id("head_username"));
email.clear();
email.sendKeys("abcd#gmail.com");
WebElement password = driver.findElement(By.id("head_password"));
password.clear();
password.sendKeys("123456");
driver.findElement(By.name("loginsubmit")).click();
}
#Test(priority = 1)
void AssertionVerification() {
// Verifying "My Account" text after login
String bodyText = driver.findElement(By.xpath("//span[#id='loginHeader']/descendant::a[text()='My Account']")).getText();
Assert.assertTrue(bodyText.contains("My Accountii"), "Not matched");
}
}
Error:
--------
FAILED: EmailPasswordEntry
java.lang.NullPointerException
at package_1.GuestCheckout.EmailPasswordEntry(GuestCheckout.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at `enter code here`org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
and same for the second Test method
Since you have instantiated WebDriver in local way and trying use that as a global instance so you are getting Null Pointer Exception. Do this in this way:
public WebDriver driver ;
public String baseURL = "http://www.ggolge.com";
#BeforeTest
public void setBaseURL(){
driver = new FirefoxDriver(); // Now this is a global instance for this class
driver.get(baseURL);
}
#Test(priority = 0)
public void EmailPasswordEntry() {
// Entering Email and Password values
driver.findElement(By.id("loginRegister")).click();
WebElement email = driver.findElement(By.id("head_username"));
email.clear();
email.sendKeys("abcd#gmail.com");
WebElement password = driver.findElement(By.id("head_password"));
password.clear();
password.sendKeys("123456");
driver.findElement(By.name("loginsubmit")).click();
}
#Test(priority = 1)
void AssertionVerification() {
// Verifying "My Account" text after login
String bodyText = driver.findElement(By.xpath("//span[#id='loginHeader']/descendant::a[text()='My Account']")).getText();
Assert.assertTrue(bodyText.contains("My Accountii"), "Not matched");
}
No it is not mandatory to run using TestNg xml, if you are using some intelligent IDE like Eclipse then you can run your tests without xml.
XMLs are beneficial when you have multiple classes to run all together as a suite.
since using webdriver... try using public static
public static webdriver driver
in each class files