1

I'm new to Selenium & new to Java as well. So maybe I'm missing something obvious, but I’m spinning on this for a while now, can't move forward & totally desperate. Please help!

Here is my set-up:

My custom Driver class implements WebDriver & sets property:

 public class Driver implements WebDriver {

    private WebDriver driver;
    private String browserName;

    public Driver(String browserName) throws Exception {
        this.browserName = browserName;
        if(browserName.equalsIgnoreCase("chrome")) {
            System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver");
            this.driver = new ChromeDriver();
        }
        else if(browserName.equalsIgnoreCase("firefox")) {
                System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver");
                this.driver = new FirefoxDriver();
            }
         else {
                throw new Exception("Browser is not correct");
            }
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        }

<...>
}

BaseTest class gets property & creates new instance of the Driver inside @BeforeClass method (browser name passed with a maven command when running the test):

String browserName = getParamater("browser");
driver = new Driver(browserName); 

In the Test class inside the @Test I create new Actions & pass there the driver from BaseTest:

Actions builder = new Actions(driver);
Action mouseOverHome = builder
        .moveToElement(pb.testGoodle)
        .build();
mouseOverHome.perform();

And this code doesn’t work -> no Actions performed (no mouse over or anything), no errors too.

However if I create & define new WebDriver inside the @Test itself:

System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver");
WebDriver driver = new FirefoxDriver();

Actions perfectly working. Any ideas or hints very appreciated!

2 Answers2

0

Resolved! Resolved! The problem was in messed Actions declaration in Page Object! Here how things look in the Page Object:

protected Driver driver;
public static Actions act;

public PlanBuilder(Driver driver) {

    this.driver = driver;
    PageFactory.initElements(driver, this);
    this.act = new Actions(driver);
}

public void rightClick (WebElement element) throws InterruptedException {
 //   Actions builder = new Actions(basedriver);
    Action openContextMenu = driver.act
            .contextClick(element)
            .build();
    openContextMenu.perform();
    Thread.sleep(4000);

}
0
public class BasePage
    {
        public static IWebDriver driver;
        public static JObject jobject;
        public static JArray jarray;
        
        public static void SeleniumInit()
        {

            BasePage.ReadJsonObject("InitData.json");
            string browser = jobject.SelectToken("browser").Value<string>();
            string Headless = jobject.SelectToken("Headless").Value<string>();
           

                if (browser == "Chrome")
                {
                    ChromeOptions options = new ChromeOptions();
                    options.AddArguments("-start-maximized");

                    if (Headless == "True")
                    {
                        options.AddArguments("-headless");
                    }

                    driver = new ChromeDriver(options);
                }
                else if (browser == "Firefox")
                {
                    FirefoxOptions options = new FirefoxOptions();
                    options.AddArguments("-start-maximized");
                    if (Headless == "True")
                    {
                        options.AddArguments("-headless");
                    }

                    driver = new FirefoxDriver(options);
                }
                else
                {
                    EdgeOptions options = new EdgeOptions();
                    options.AddArguments("-start-maximized");
                    if (Headless == "True")
                    {
                        options.AddArguments("-headless");
                    }

                    driver = new EdgeDriver(options);
                }
            
        }

        public static void Write(By by, string user)
        {
            try
            {
                driver.FindElement(by).SendKeys(user);
                TakeScreenshot(Status.Pass, "Write " + user);
            }
            catch (Exception ex)
            {
                TakeScreenshot(Status.Fail, "Write Failed: " + ex.ToString());
                Assert.Fail();
            }
        }

        public static void Click(By by)
        {
            try
            {
                driver.FindElement(by).Click();
                TakeScreenshot(Status.Pass, "Click");
            }
            catch (Exception ex)
            {
                TakeScreenshot(Status.Fail, "Click Failed: " + ex.ToString());
                Assert.Fail();
            }
        }

        public static void OpenUrl(string url)
        {
            try
            {
                driver.Url = url;
                TakeScreenshot(Status.Pass, "Open url: " + url);
            }
            catch (Exception ex)
            {
                TakeScreenshot(Status.Fail, "Open Url Failed: " + ex.ToString());
                Assert.Fail();
            }
        }

        public static void Clear(By by)
        {
            try
            {
                driver.FindElement(by).Clear();
                TakeScreenshot(Status.Pass, "Clear Text: " );
            }
            catch (Exception ex)
            {
                TakeScreenshot(Status.Fail, "Clear Text Failed: " + ex.ToString());
                Assert.Fail();
            }
        }
        public static void ClickRadio(By by)
        {

            try
            {
                Actions actions = new Actions(driver);
                IWebElement radioLocator = driver.FindElement(by);
                actions.Click(radioLocator).Build().Perform();
                TakeScreenshot(Status.Pass, "Click Radio Button");
            }
            catch (Exception ex)
            {
                TakeScreenshot(Status.Fail, "Radio Button Click Failed: " + ex.ToString());
                Assert.Fail();
            }
        }

        public static void SelectOption(By by, string value)
        {
            try
            {
                var dropdown = driver.FindElement(by);
                var selectDropdown = new SelectElement(dropdown);
                selectDropdown.SelectByValue(value);
                TakeScreenshot(Status.Pass, "Select Option from Dropdown Menu");
            }
            catch (Exception ex)
            {
                TakeScreenshot(Status.Fail, "Select Option Failed: " + ex.ToString());
                Assert.Fail();
            }
        }
            public static string GetElementText(By by)
            {
                string text;
                try
                {
                    text = driver.FindElement(by).Text;
                }
                catch
                {
                    try
                    {
                        text = driver.FindElement(by).GetAttribute("value");
                    }
                    catch
                    {
                        text = driver.FindElement(by).GetAttribute("innerHTML");
                    }
                }
                return text;
            }

        public static void Assertion(By by, string assertText)
        {
            try {
                string Text = GetElementText(by);
                Assert.AreEqual(assertText, Text);
                TakeScreenshot(Status.Pass, "Assertion Passed");
            }
            catch (Exception ex)
            {
                TakeScreenshot(Status.Fail, "Assertion Failed: " + ex.ToString());
                Assert.Fail();
            }

        }

        public static void sleep()
        {
            Thread.Sleep(10000);
        }
        public static string GetElementState(By by)
        {
            string elementState = driver.FindElement(by).GetAttribute("Disabled");
            if (elementState == null)
            {
                elementState = "enabled";
            }
            else if (elementState == "true")
            {
                elementState = "disabled";
            }
            return elementState;

        }
        public static void ExplicitWait(By by)
        {
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
            wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(by));
            //wait.Until(Driver => IsPageReady(Driver) == true && IsElementVisible(by) == true && IsClickable(by) == true);
            //wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
            //wait.Until(driver => IsElementVisible(driver, By.Id("username")) == true);
        }


        public static void ImplicitWait()
        {
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
        }

        public static void FluentWait()
        {
            DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(driver);
            fluentWait.Timeout = TimeSpan.FromSeconds(60);
            fluentWait.PollingInterval = TimeSpan.FromMilliseconds(250);
            /* Ignore the exception - NoSuchElementException that indicates that the element is not present */
            fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException));
            fluentWait.Message = "Element to be searched not found";
        }

        public static void scrollDown()
        {
            IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
            js.ExecuteScript("window.scrollTo(0, document." + "Body" + ".scrollHeight);");
        }

        public static void switchWindow()
        {
            driver.SwitchTo().Window(driver.WindowHandles[1]);
        }

        public static void TakeScreenshot(Status status, string stepDetail)
        {
            string path = @"C:\ExtentReports\" + "TestExecLog_" + DateTime.Now.ToString("yyyyMMddHHmmss");

            Screenshot image = ((ITakesScreenshot)driver).GetScreenshot();
            image.SaveAsFile(path + ".png", ScreenshotImageFormat.Png);
            ExtentReport.exChildTest.Log(status, stepDetail, MediaEntityBuilder.CreateScreenCaptureFromPath(path + ".png").Build());
        }

        public static void ReadJson(string filename)
        {
            string myJsonString = File.ReadAllText(@"..\\..\\..\\" + filename);
            jarray = JArray.Parse(myJsonString);
        }
        public static void ReadJsonObject(string filename)
        {
            string myJsonString = File.ReadAllText(@"..\\..\\..\\" + filename);
            jobject = JObject.Parse(myJsonString);
        }
    }
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 25 '23 at 09:48