Unable to load chrome/gecko driver after using Cucumber Driver Factory - nullpointerexception

This is my first question ever asked here, so I hope I ask it the right way:
I'm working on a multimodule maven project to test a software that is still in a development. I've been using Cucumber, Selenium, JUnit for some time and doing online courses to improve my skills. In one of the tutorials was explained how to use Driver Factory and configuration files so I applied it to my project, but after that was unable to run any of the drivers (gecko/chrome/ie). Here is a big part of the code, so I hope someone can help :)
I catch the exception from the DriverFactory.class:
"Unable to load browser: null"
config.properties file has only one line:
browser=chrome
public class DriverFactory {
public static WebDriver driver;
public WebDriver getDriver() {
try {
//Read Config
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (driver == null) {
System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
FirefoxOptions options = new FirefoxOptions();
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
}
break;
case "chrome":
if (driver == null) {
System.setProperty("webdriver.chrome.driver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
driver.manage().window().maximize();
}
break;
/*case "ie":
if (driver == null) {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", Constant.IE_DRIVER_DIRECTORY);
capabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
}
*/
}
} catch (Exception e) {
System.out.println("Unable to load browser: " + e.getMessage());
} finally {
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
return driver;
}
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");
}
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties\\config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\geckodriver.exe";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\chromedriver.exe";
public class CreateCaseSteps extends DriverFactory {
//Background Steps
#Given("^user accesses the login page$")
public void userAccessesTheLoginPage() throws Throwable {
getDriver().get("http://localhost:8080/");
}
#When("^user enters a valid username")
public void userEntersAValidUsername(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='username']")).sendKeys(data.get(0).get(0));
}
#When("^user enters a valid password")
public void userEntersAValidPassword(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='password']")).sendKeys(data.get(0).get(0));
}
#And("^user clicks on the login button$")
public void userClicksOnTheLoginButton() throws Throwable {
getDriver().findElement(By.xpath("//input[#value='Login']")).click();
}
#Then("^user should be taken successfully to the login page$")
public void userShouldBeTakenSuccessfullyToTheLoginPage() throws Throwable {
Thread.sleep(3000);
WebElement logoutMenu = getDriver().findElement(By.xpath("//i[#class='glyphicon glyphicon-user']"));
Assert.assertEquals(true, logoutMenu.isDisplayed());
}

Related

Selenium web driver and csv file

I have data in csv file and also integrate with Selenium.
The test scenario is Search the name of product and verify that the Product name, category, Brand and sub-category according to the document or not? Please Help if it is possible.
Here is my code
public class ProductVerification {
public String baseurl="https://souqofqatar.com/admin";
String driverPath="C:\\Users\\Novatore\\Desktop\\Selenium-Drivers\\chromedriver.exe";
String CSV_file="CSVdatafile\\Cat-Home Appliances and SubCat-Home Comfort (1).csv";
static WebDriver driver;
String line="";
#BeforeMethod
public void launchBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver",driverPath);
driver =new ChromeDriver();
driver.get(baseurl);
driver.manage().window().maximize(); driver.findElement(By.xpath("//[#id=\"admin_user_email\"]")).sendKeys("admin#example.com");
driver.findElement(By.xpath("//*[#id=\"admin_user_password\"]")).sendKeys("password");
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/div/form/fieldset[2]/ol/li/input")).click();
driver.findElement(By.xpath("/html/body/div[1]/div[1]/ul[1]/li[5]/a")).click();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(450,0)", "");
Thread.sleep(3000);
}
#Test
public void search() throws InterruptedException, IOException, CsvException {
File file = new File(CSV_file);
if(file.exists()){
System.out.println("File Exists");
}
try {
BufferedReader br=new BufferedReader(new FileReader(file));
while((line=br.readLine()) !=null){
while((line=br.readLine()) !=null) {
String[] values = line.split(",");
String row= (values[1]);
for (int i=0; row!=null;i++) {
driver.findElement(By.xpath("//*[#id=\"q_name\"]")).sendKeys(""+row);
Thread.sleep(5000);
driver.findElement(By.xpath("/html/body/div[1]/div[4]/div[2]/div/div/form/div[9]/input[1]")).click();
Thread.sleep(3000);
String name=driver.findElement(By.xpath("//td[#class='col col-name']")).getText();
System.out.println(name);
if(name!=row) {
System.out.println(name+" Not find");
}
}
}
}}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}
#AfterMethod
public void CloseBrowser() {
driver.close();
}
}

NullPointerException error i.e. AndroidDriver not gets initialized for the second test class as It's working fine for the first test class

This is My setup class:
public class SetupClass {
//AppiumDriver<MobileElement> driver;
AndroidDriver<MobileElement> d;
public Properties prop =null;
public File file;
public FileInputStream fis;
#Parameters(value ="Android")
#BeforeSuite
public void setup(String Android) throws IOException, Exception{
LoadPropertiesFile();
DesiredCapabilities caps = new DesiredCapabilities();
/*caps.setCapability("plateformName", "Android");
caps.setCapability(CapabilityType.PLATFORM_NAME, "Android");*/
if (Android.equalsIgnoreCase("Moto_g4_Plus")) {
caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.0");
caps.setCapability(MobileCapabilityType.UDID, "ZY223WZSQ9");
caps.setCapability(MobileCapabilityType.DEVICE_NAME, "Moto G4 Plus");
}
caps.setCapability("app", "C:\\Users\\amarjeet.sharma\\eclipse-workspace\\com.asm.app\\src\\test\\resources\\app\\asmVisit.apk");
caps.setCapability("appPackage", "com.sumasoft.net.asmscheduler");
caps.setCapability("appActivity", "md5f32326382a711c73d2de951d70f3bd5e.MainActivity");
caps.setCapability("autoGrantPermissions", true);
URL url;
try {
url = new URL("http://127.0.0.1:4723/wd/hub");
//driver = new AppiumDriver<MobileElement>(url, caps);
d = new AndroidDriver<MobileElement>(url, caps);
Thread.sleep(5000);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("Cause is:" +e.getCause());
System.out.println("Message is:" +e.getMessage());
e.printStackTrace();
}
}
public void LoadPropertiesFile() throws IOException {
prop=new Properties();
file =new File(System.getProperty("user.dir")+"/src/main/resources/config.properties");
fis=new FileInputStream(file);
prop.load(fis);
//System.out.println(prop.getProperty("userId"));
}
//#AfterTest
public void TearDown() throws IOException{
System.out.println("Quit");
d.quit();
}
}
This is My LoginTest
public class LoginTest extends SetupClass{
#Test(priority = 1)
public void login() throws Exception {
LoginPage lp = new LoginPage(d);
//System.out.println(prop.getProperty("userId"));
lp.userName(prop.getProperty("userId"));
Thread.sleep(500);
lp.password(prop.getProperty("Passwd"));
Thread.sleep(500);
lp.loginButton();
}
}
And this is my create new journey class
public class AddJourneyTest extends SetupClass{
#Test(priority=2)
public void AddNewJourney() throws Exception {
AddjourneyPage addobj = new AddjourneyPage(d);
addobj.ClicktoAdd();
addobj.SelectFromToDate();
addobj.SelectState();
addobj.SelectCity();
addobj.ClickonSubmit();
}
}
I am getting NullPointerException for AddJourney class
I think when I run it as TestNG then the driver gets initiated for the LoginTest and holds the control. So that AddJourney class does not get driver initiated and hence getting NullPointerException.
I am using Appium Server, Java + Selenium + TestNG for the Android Application automation on Windows system with physical android device.
Maybe I am wrong. But I am not getting solution over it. Please help.

"No tests found. Nothing was run" message in console , unable to understand why

Below is the code am trying to execute
Not sure why am getting [TestNG] No tests found. Nothing was run
if I remove the before class annotation method, it executes but fails due the dependency
public class TestNG_Practice3 {
static WebDriver driver ;
String url = "https://in.linkedin.com/";
#BeforeClass(description = "To open the browser")
public void openBrowser()
{ driver = new FirefoxDriver();
driver.get(url);
System.out.println("Browser got open");
}
#Test (dependsOnMethods ="openBrowser",description = "To signin")
public void login()
{
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);
WebElement signin = driver.findElement(By.id("login-email"));
Assert.assertTrue(signin.isDisplayed());
WebElement password = driver.findElement(By.id("login-password"));
WebElement signinbutton = driver.findElement(By.id("login-submit"));
signin.sendKeys("xyz");
password.sendKeys("abc");
signinbutton.click();
Assert.assertTrue(driver.getCurrentUrl().contains("feed/"));
}
#Test(dependsOnMethods = "login")
public void logout()
{
WebElement meDropdown = driver.findElement(By.xpath("//*[#id=\"nav-settings__dropdown-trigger\"]/div/span[2]/li-icon/svg"));
meDropdown.click();
WebElement logout = driver.findElement(By.id("ember545"));
logout.click();
}
#AfterClass
public void closebrowser()
{
driver.quit();
}
}
Step-1 : Basic trial with Project Build,
public class TestNG_Demo {
#BeforeClass
public void openbrowser()
{
System.out.println("Browser got open");
}
#Test
public void testbrowser()
{
System.out.println("Test execution");
}
#AfterClass
public void closebrowser()
{
System.out.println("Browser got close");
}
}
So you will be have idea, Your project build get successful execution.
If you have maven project and Build did not get pass, you will be have trigger what is causing from maven build dependency.
Update
Step-2 : After tracing first trial
public class TestNG_Demo {
#Test
public void testbrowser()
{
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
}
}
Remove dependsOnMethods ="openBrowser" because it's not a test method and will be execute before test without it

Extent Reports tests always reporting Pass

I am having an issue where if I run a test that has 6 steps, 3 pass, 1 fail, 2 skipped. It will always report as Passed in my extent reports. I am using Klov. Is it possible that I have not correctly configured the report? and if so does anyone have suggestions to fix this issue.
public class MyRunner {
#BeforeClass
public static void initialize(){
d = new Date();
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setKlovServerUrl("http://localhost");
extentProperties.setKlovProjectName("Test Project");
extentProperties.setKlovReportName("Test Report: " + d);
extentProperties.setMongodbHost("localhost");
extentProperties.setMongodbPort(27017);
extentProperties.setMongodbDatabase("klov");
}
}
#AfterClass
public static void teardown(ITestResult result){
extent.flush();
}
}
And here is my test, it is just a simple test that opens googles login page, just to make sure the extent reports will do everything I need it to
public class Google {
WebDriver driver;
#Given("^that I am on the webpage Google$")
public void thatIAmOnTheWebpageGoogle() throws Throwable {
System.setProperty("webdriver.chrome.driver","\\\\hiscox.nonprod\\profiles\\Citrix\\XDRedirect\\CaseyG\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://accounts.google.com/signin/v2/identifier?hl=en&passive=true&continue=https%3A%2F%2Fwww.google.com%2F&flowName=GlifWebSignIn&flowEntry=ServiceLogin");
driver.manage().window().maximize();
MyRunner.logger.log(Status.INFO, "Opened Google login page")
//throw new PendingException();
//extent.createTest("Step 1").pass("log");
}
#When("^I try to login$")
public void i_try_to_login() throws Throwable {
// find the username field and enters the username, then clicks next
WebElement username = driver.findElement(By.xpath("//input[#id='identifierId']"));
username.sendKeys("********");
driver.findElement(By.id("identifierNext")).click();
//finds the password field and enters the password
WebElement password = driver.findElement(By.xpath("//input[#name='password']"));
password.sendKeys("**********");
Assert.assertFalse(true);
driver.findElement(By.id("passwordNext")).click();
//throw new PendingException();
//extent.createTest("Step 2").pass("log");
}
#Then("^I will be successfully logged into Google$")
public void i_will_be_successfully_logged_into_Google() throws Throwable {
String account = "Google Account: greg casey \n" + "(klovtest#gmail.com)";
//WebElement loggedInUser = driver.findElement(By.xpath("//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]"))
//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]/a
//extent.createTest("Step 3").pass("log");
throw new PendingException();
}
}
You should use ITestListener Interface on your Listener class where extent report's test is created
OnTestStart and do other things alos as descriobed below (I have used Thread for parallel device testing so you can ignore, rest is useful)
public class Listeners extends Utilities implements ITestListener {
ExtentReports extent = ExtentReporterTool.getReport();enter code here
ExtentTest test;
ThreadLocal<ExtentTest> testObjects = new ThreadLocal<ExtentTest>();
#Override
public void onTestStart(ITestResult result) {
test = extent.createTest(result.getMethod().getMethodName());
testObjects.set(test);
}
#Override
public void onTestSuccess(ITestResult result) {
testObjects.get().log(Status.PASS, "Test Case passed");
}
#Override
public void onTestFailure(ITestResult result) {
testObjects.get().fail(result.getThrowable());
WebDriver driver;
try {
driver = (WebDriver) result.getTestClass().getRealClass().getSuperclass().getField("driver")
.get(result.getInstance()); testObjects.get().addScreenCaptureFromPath(takeScreenshot(result.getMethod().getMethodName(), driver),
result.getMethod().getMethodName());
} catch (IOException | IllegalArgumentException | SecurityException | IllegalAccessException
| NoSuchFieldException e) {
e.printStackTrace();
}
}
#Override
public void onTestSkipped(ITestResult result) {
testObjects.get().log(Status.SKIP, "Test Case skipped");
}
#Override
public void onFinish(ITestContext context) {
extent.flush();
}
}

How can I run the same test on browserstack and local browsers?

I've set up NUnit tests that runs on BrowserStack (set up from this example https://github.com/browserstack/nunit-browserstack )
Base class:
namespace Bloc.TestProject
{
public class BrowserStackNUnitTest
{
protected IWebDriver driver;
protected string profile;
protected string environment;
private Local browserStackLocal;
public BrowserStackNUnitTest(string profile, string environment)
{
this.profile = profile;
this.environment = environment;
}
[SetUp]
public void Init()
{
...
Browserstack tests:
namespace Bloc.TestProject
{
[TestFixture("parallel", "chrome")]
[TestFixture("parallel", "ie11")]
[TestFixture("parallel", "iphoneX")]
[TestFixture("parallel", "ipad")]
[TestFixture("parallel", "samsungGalaxyS8")]
[Parallelizable(ParallelScope.Fixtures)]
public class OnTimeOnlineBooking : BrowserStackNUnitTest
{
WebDriverWait wait;
public OnTimeOnlineBooking(string profile, string environment) : base(profile, environment)
{
}
... my tests ...
Local tests:
namespace Bloc.TestProject
{
[TestFixture(typeof(PhantomJSDriver))]
public class LocalBrowserTest<TWebDriver> where TWebDriver : IWebDriver, new()
{
private IWebDriver driver;
[SetUp]
public void CreateDriver()
{
this.driver = new TWebDriver();
}
[TearDown]
public void Cleanup()
{
driver.Quit();
}
... my tests ...
Is there any way I can structure my tests so that I can run a test and it'll run both locally and on browserstack without having to duplicate the test code?
I can Suggest a workaround for this case in Java, needs to change in C#.
write the code of browser-stack setup
public static browserstack_setup() {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserName", "chrome");
caps.setCapability("version", "");
caps.setCapability("platform", "windows");
caps.setCapability("os_version", "8.1");
WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
driver.get("http://www.google.com");
}
then write code for launch browser
public void openbrowser(String browsername, String URL){
if(browsername.equalsIgnoreCase("broserstack")){
browserstack_setup();
}else if(browsername.equalsIgnoreCase("CH")){
System.setProperty("webdriver.chrome.driver",chromedriverpath);
driver=new ChromeDriver();
driver.get(URL);
}
}
You may fetch the name from test context and based on that information, launch the local driver or remote driver. For the repo and you example, I assume the below code should work. You may also want to look at other APIs available under TestContext.CurrentContext.Test for your comparison operation
[SetUp]
public void Init()
{
if(TestContext.CurrentContext.Test.Name == "MyTestName"){
this.driver = new TWebDriver();
}
else{
NameValueCollection caps = ConfigurationManager.GetSection("capabilities/" + profile) as NameValueCollection;
NameValueCollection settings = ConfigurationManager.GetSection("environments/" + environment) as NameValueCollection;
DesiredCapabilities capability = new DesiredCapabilities();
foreach (string key in caps.AllKeys)
{
capability.SetCapability(key, caps[key]);
}
foreach (string key in settings.AllKeys)
{
capability.SetCapability(key, settings[key]);
}
String username = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME");
if(username == null)
{
username = ConfigurationManager.AppSettings.Get("user");
}
String accesskey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY");
if (accesskey == null)
{
accesskey = ConfigurationManager.AppSettings.Get("key");
}
capability.SetCapability("browserstack.user", username);
capability.SetCapability("browserstack.key", accesskey);
if (capability.GetCapability("browserstack.local") != null && capability.GetCapability("browserstack.local").ToString() == "true")
{
browserStackLocal = new Local();
List<KeyValuePair<string, string>> bsLocalArgs = new List<KeyValuePair<string, string>>();
bsLocalArgs.Add(new KeyValuePair<string, string>("key", accesskey));
browserStackLocal.start(bsLocalArgs);
}
driver = new RemoteWebDriver(new Uri("http://"+ ConfigurationManager.AppSettings.Get("server") +"/wd/hub/"), capability);
}
}
You need to ensure you have specified test fixtures for running on Local and Grid. For example, if test A on Safari on Grid and test A on local browser