How to prevent StaleElementReferenceException in PageFactory in Selenium C#? - c#

I have a Selenium WebDriver Page Object Model in C# 6. I am experiencing StaleElementReferenceExceptions while trying to click on ajax-loaded nav bar elements. This is confusing, because I'm using PageFactory, without any [CacheLookup]s.
Here's the code in question. I've tried to simplify to just the important parts. (I actually pass around a Driver, a wrapper around IWebDriver.) MenuBar.SelectEnglish<T>() throws the exception.
public class Tests
{
[Test]
public void SelectEnglishTest()
{
homePage
.MenuBar.SelectEnglish<HomePage>();
}
// ...
}
public class MenuBar : PageObject
{
[FindsBy(How = How.CssSelector, Using = "...")]
private IWebElement Language { get; set; }
[FindsBy(How = How.CssSelector, Using = "...")]
private IWebElement English { get; set; }
public T SelectEnglish<T>() where T : Page
{
Language.Click();
IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.ElementToBeClickable(English));
English.Click();
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
return (T)Activator.CreateInstance(typeof(T), Driver);
}
// ...
}
public class HomePage : PageObject
{
public MenuBar MenuBar { get; private set; }
// ...
}
public class PageObject
{
protected IWebDriver Driver { get; }
protected PageObject(IWebDriver driver)
{
Driver = driver;
PageFactory.InitElements(this, new RetryingElementLocator(Driver, TimeSpan.FromSeconds(20)));
}
// ...
}
What is causing this error? What can I do about it?

From the docs, Stale Element Reference Exception
A stale element reference exception is thrown in one of two cases, the first being more common than the second:
- The element has been deleted entirely.
- The element is no longer attached to the DOM.
Since you mentioned the element is loaded using Ajax, most likely the element changed after your page object fetched it. Just fetch it again or wait for the Ajax to complete before fetching the affected elements.
EDIT 1
Here's some sample code to show how you can fetch an element using a method even while using PageFactory.
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.PageObjects;
using System;
namespace C_Sharp_Selenium_Test
{
class Program
{
static void Main(string[] args)
{
FirefoxDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com");
HomePage homePage = new HomePage(driver);
PageFactory.InitElements(driver, homePage);
homePage.search("stack overflow");
homePage.getSearchBox().Clear();
homePage.getSearchBox().SendKeys("c# pagefactory");
homePage.getSearchButton().Click();
}
}
public class HomePage
{
private By searchBox = By.Id("lst-ib");
private By searchButton = By.Name("btnG");
// add other elements in here that use FindsBy() to be loaded using PageFactory.InitElements()
private IWebDriver driver;
public void search(String s)
{
getSearchBox().SendKeys(s);
getSearchButton().Click();
}
public IWebElement getSearchBox()
{
return driver.FindElement(searchBox);
}
public IWebElement getSearchButton()
{
return driver.FindElement(searchButton);
}
public HomePage(IWebDriver driver)
{
this.driver = driver;
}
}
}

Related

Sharing Driver between Step files in C#

I'm having an issue with sharing my driver between step files in my projects. I've done a lot of googling online and come up with a solution using the IObjectContainer. Which I believe is correct? However, it doesn't seem to work. It gets stuck. I don't quite understand where IObjectContainer gets instantiated. Below is the code of my Hooks file and one of my Step Files:
Hooks File:
public class RDM_Hooks
{
private IObjectContainer _objectContainer;
public RDM_Website<ChromeDriver> RDM_Website;
public void WebDriverSupport(IObjectContainer objectContainer)
{
_objectContainer = objectContainer;
}
[BeforeScenario]
public void InitWebDriver()
{
RDM_Website = new RDM_Website<ChromeDriver>();
_objectContainer.RegisterInstanceAs<RDM_Website<ChromeDriver>>(RDM_Website);
}
[AfterScenario]
public void DisposeWebDriver()
{
RDM_Website.SeleniumDriver.Quit();
RDM_Website.SeleniumDriver.Dispose();
}
}
Steps File:
public class RDM_LoginSteps
{
private RDM_Website<ChromeDriver> RDM_Website;
public RDM_LoginSteps(RDM_Website<ChromeDriver> rdm_website)
{
RDM_Website = rdm_website;
}
[Given(#"I am on the homepage")]
public void GivenIAmOnTheHomepage()
{
RDM_Website.RDM_Homepage.VisitHomePage();
}
}
I think im missing something somewhere but any info i've found online doesn't go further than the above and I'm a bit lost.
I simply want all my step files to share the same browser so I'm able to have all my login steps using one file and do something else on another for example.
Here's the Hook file I use my UI tests
[Binding]
internal sealed class WebHooks
{
private readonly IObjectContainer _objectContainer;
public WebHooks(IObjectContainer objectContainer)
{
_objectContainer = objectContainer;
}
[BeforeScenario("web")]
public void BeforeWebScenario()
{
//HACK:
//https://stackoverflow.com/questions/43571119/loading-of-unpacked-extensions-is-disabled-by-the-administrator
var options = new ChromeOptions();
options.AddArgument("--start-maximized");
options.AddAdditionalCapability("useAutomationExtension", false);
options.AddArgument("--no-sandbox");
options.AddArgument("--whitelisted-ips=''");
//HACK: this fixes issue with not being able to find chromedriver.exe
//https://stackoverflow.com/questions/47910244/selenium-cant-find-chromedriver-exe
var webDriver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options, TimeSpan.FromMinutes(15));
webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(40);
_objectContainer.RegisterInstanceAs<IWebDriver>(webDriver);
}
[AfterScenario("web")]
public void AfterWebScenario()
{
var webDriver = _objectContainer.Resolve<IWebDriver>();
if (webDriver == null) return;
webDriver.Close();
webDriver.Dispose();
}
}
It looks like you're missing the [Binding] attribute on the hook class.
I also don't see you getting the reference out of the container to Dispose of it when you are done.
I don't know what RDM_Website is doing, but I'd keep you hooks clean with just reference to the driver and nothing else.
Then reference it in your step class like
[Binding]
public class Steps
{
private readonly IWebDriver _webDriver;
public Steps(IWebDriver webDriver)
{
_webDriver = webDriver;
}
}
the BoDi container is already hooked up for you

Sharing the dirver object initialized in base class to that of page classes

In the POM model, we ideally tend to have the driver object being initialized in base class. And in the page classed we pass this driver object. But the problem is to avoid passing this object as well and the tests should continue to work in parallel too in XUNit framework. Below is the structure
public class BaseClass:IDisposable
{
public IWebDriver Driver{get;set;}
public BaseClass()
{
if(Driver == null)
{
Driver = new ChromeDriver();
}
}
}
public class Page1:BaseClass
{
public void method1()
{
this.Driver.Navigate.GoToUrl("http://www.google.com")
}
}
public class Page2:BaseClass
{
public void method2()
{
this.Driver.Navigate.GoToUrl("http://www.stackoverflow.com")
}
}
public class TestClass
{
[Fact]
public void Test1()
{
new Page1().method1();
new Page2().method2();
}
}
Now in the above structure if the test executes two instances of the driver object will be created because of OOPS. If we need to avoid this we can the Driver object as static and reinitialize it if the object is null. But this will again fail when we run multiple tests in parallel. Any suggession? Thing I am trying to achieve is that full encapsulation where the Test class should not have any access to Selenium objects. These objects should be only accessible in Page class or its Operation class if we have any.
We need to ensure we create a driver singleton and its threadsafe to run parallely
[TestClass]
public class UnitTest1 : TestBase
{
[TestMethod]
public void TestMethod1()
{
new Page1().method1();
new Page2().method2();
Driver.Testcleanup();
}
[TestMethod]
public void TestMethod2()
{
new Page1().method1();
new Page2().method2();
Driver.Testcleanup();
}
public class Page1
{
public void method1()
{
Driver.Instance.Navigate().GoToUrl("http://www.google.com");
}
}
public class Page2
{
public void method2()
{
Driver.Instance.Navigate().GoToUrl("http://www.google.com");
}
}
}
Driver Class will handle the initialization of the singleton and cleanup
public sealed class Driver
{
[ThreadStatic]
public static IWebDriver driver = null;
public static IWebDriver Instance
{
get
{
if (driver == null)
{
driver = new ChromeDriver();
}
return driver;
}
}
public static void Testcleanup()
{
driver.Quit();
driver = null;
}
}

C# Extending Selenium Webdriver Class

I would like to add a static string property that will track the name of the current test running. I figured the best way to go about this was to use the WebDriver since it is the only object that is carried throughout all of my page objects.
Is there a way to extend the WebDriver class to add a string property that I can set?
EDIT: Since WebDriver uses the IWebDriver interface rather would I extend the interface perhaps?
EDIT #2: Adding example of what I currently have to load my WebDriver:
protected static NLog.Logger _logger = LogManager.GetCurrentClassLogger();
protected static IWebDriver _driver;
/// <summary>
/// Spins up an instance of FireFox webdriver which controls the browser using a
/// FireFox plugin using a stripped down FireFox Profile.
/// </summary>
protected static void LoadDriver()
{
ChromeOptions options = new ChromeOptions();
try
{
var profile = new FirefoxProfile();
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream doc xls pdf txt");
_driver = new FirefoxDriver(profile);
_driver.Navigate().GoToUrl("http://portal.test-web01.lbmx.com/login?redirect=%2f");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
Ok let's stop the half answer practice (That is the full implementation of generic IWebDriver) after that you can call all the regular methods like you use in standard driver + you have your additional CurrentTest variable.
you can add more constructors for best compatibility.
class MyWebDriver<T> where T : IWebDriver, new()
{
IWebDriver driver;
public string CurrentTest { get; set; }
public MyWebDriver()
{
driver = new T();
}
public void Dispose()
{
this.driver.Dispose();
}
public IWebElement FindElement(By by)
{
return this.driver.FindElement(by);
}
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
return this.driver.FindElements(by);
}
public void Close()
{
this.driver.Close();
}
public void Quit()
{
this.driver.Quit();
}
public IOptions Manage()
{
return this.driver.Manage();
}
public INavigation Navigate()
{
return driver.Navigate();
}
public ITargetLocator SwitchTo()
{
return this.SwitchTo();
}
public string Url
{
get
{
return this.driver.Url;
}
set
{
this.driver.Url = value;
}
}
public string Title
{
get
{
return this.driver.Title;
}
}
public string PageSource
{
get
{
return this.driver.PageSource;
}
}
public string CurrentWindowHandle
{
get
{
return this.driver.CurrentWindowHandle;
}
}
public ReadOnlyCollection<string> WindowHandles
{
get
{
return this.WindowHandles;
}
}
}
public class MyTest
{
public void main()
{
MyWebDriver<FirefoxDriver> driver = new MyWebDriver<FirefoxDriver>();
driver.CurrentTest = "Entering to google website with Firefox Driver";
driver.Navigate().GoToUrl("www.google.com");
}
}
You will need to wrap the WebDriver using the "Decorator" design pattern.
public class MyWebDriver : IWebDriver
{
private IWebDriver webDriver;
public string CurrentTest { get; set; }
public MyWebDriver(IWebDriver webDriver)
{
this.webDriver = webDriver
}
public Method1()
{
webDriver.Method1();
}
public Method2()
{
webDriver.Method2();
}
...
}
And then pass in whichever driver you are using at the time.
var profile = new FirefoxProfile();
MyWebDriver driver = new MyWebDriver(new FirefoxDriver(profile));
This way you are delegating the interface methods of IWebDriver to FirefoxDriver but can add whatever additions are appropriate.
what if you do something like
class MyWebDriver
{
private IWebDriver driver;
private static string CurrentTest;
....
//make constractors / getters, setters
}
execution
MyWebDriver d = new MyWebDriver(....)
...
Just use a sub class that has WebDriver as its parent:
public class MyWebDriver : WebDriver
{
private string _currentTest;
}
Then you can use MyWebDriver everywhere and set _currentTest as needed.

Xunit create new instance of Test class for every new Test ( using WebDriver and C#)

Is there any way to run multiple tests in same browser using Webdriver (Selenium) using Xunit, , at present xunit launches new browser for every new test , below is the sample code
public class Class1
{
private FirefoxDriver driver;
public Class1()
{
driver = new FirefoxDriver();
}
[Fact]
public void Test()
{
driver.Navigate().GoToUrl("http://google.com");
driver.FindElementById("gbqfq").SendKeys("Testing");
}
[Fact]
public void Test2()
{
driver.Navigate().GoToUrl("http://google.com");
driver.FindElementById("gbqfq").SendKeys("Testing again");
}
}
While I don't know Selenium, I do know that xUnit.net creates a new instance of your test class for every test method, so that probably explains why you are seeing the behaviour you're reporting: the driver field is initialized anew for each test method, because the constructor is invoked every time.
In order to reuse a single FirefoxDriver instance, you can use xUnit.net's IUseFixture<T> interface:
public class Class1 : IUseFixture<FirefoxDriver>
{
private FirefoxDriver driver;
public void SetFixture(FirefoxDriver data)
{
driver = data;
}
[Fact]
public void Test()
{
driver.Navigate().GoToUrl("http://google.com");
driver.FindElementById("gbqfq").SendKeys("Testing");
}
[Fact]
public void Test2()
{
driver.Navigate().GoToUrl("http://google.com");
driver.FindElementById("gbqfq").SendKeys("Testing again");
}
}
after some investigation able to find the solution here it is and also updated FirefoxDriver to IWebDriver::
public class SampleFixture : IDisposable
{
private IWebDriver driver;
public SampleFixture()
{
driver = new FirefoxDriver();
Console.WriteLine("SampleFixture constructor called");
}
public IWebDriver InitiateDriver()
{
return driver;
}
public void Dispose()
{
// driver.Close();
driver.Quit();
Console.WriteLine("Disposing Fixture");
}
}
public class Class1 : IUseFixture<SampleFixture>
{
private IWebDriver driver;
public void SetFixture(SampleFixture data)
{
driver = data.InitiateDriver();
}
[Fact]
public void Test()
{
driver.Navigate().GoToUrl("http://google.com");
driver.FindElement(By.Id("gbqfq")).SendKeys("Testing");
}
[Fact]
public void Test2()
{
driver.Navigate().GoToUrl("http://google.com");
driver.FindElement(By.Id("gbqfq")).SendKeys("Testing again");
}
}
IUseFixture doesn't exist any more and seems replaced by IClassFixture. But I can't directly inject the FirefoxDriver as posted by #Mark Seemann:
public class DashboardCategoryBoxes : IClassFixture<FirefoxDriver> {
IWebDriver driver;
public DashboardCategoryBoxes(FirefoxDriver driver) {
//this.driver = wrapper.Driver;
this.driver = driver;
}
}
This throw an error
System.AggregateException : One or more errors occurred. (Class fixture type 'OpenQA.Selenium.Firefox.FirefoxDriver' may only define a single public constructor.) (The following constructor parameters did not have matching fixture data: FirefoxDriver driver)
---- Class fixture type 'OpenQA.Selenium.Firefox.FirefoxDriver' may only define a single public constructor.
---- The following constructor parameters did not have matching fixture data: FirefoxDriver driver
As a workaround, we could create some wrapper class without constructor
public class FirefoxWrapper {
FirefoxDriver driver = new FirefoxDriver();
public FirefoxWrapper Driver {
get { return driver; }
}
}
and fetch the driver from there
public class DashboardCategoryBoxes : IClassFixture<FirefoxWrapper> {
IWebDriver driver;
public DashboardCategoryBoxes(FirefoxWrapper wrapper) {
driver = wrapper.Driver;
}
}

webdriver modal window click() not working

I've been browsing around trying to find a solution to this but none of the solutions have worked for me thus far.
Here is a quick test I've thrown together where its simply trying to click the 'close' button to close a modal pop up. I can step through my test in Visual Studio and it will work fine. When I run the test in Nunit, it will error. I've tried the following based upon others issues and suggestions given to them:-
putting in waits all over the place
changing from the chrome driver to firefox
changing to maximised window mode
re-working it every which way I can think of
The modal is not an iframe or anything like that. I seem to be getting the following error:
Exception has been thrown by the target of an invocation.
----> System.InvalidOperationException : Element is not clickable at point (922.5, 342.0999755859375). Other element would receive the click:
which is why I was fiddling with maximised and normal sized modes.
Looking for any suggestions as it's got me stumped..
Thanks
[Test(Description = "Test to check if the cancel button closes the modal window when clicked on the 'Reset Password' modal")]
public void CheckCancelPasswordResetOnModalWorks()
{
bool modalFoundSuccess = false;
bool forgotPasswordControlFound = false;
_driver.Navigate().GoToUrl(_baseURL + "login");
if (_loginPage.CheckForgotPasswordControlExists())
{
forgotPasswordControlFound = true;
_loginPage.ClickForgotPasswordButton();
if (_loginPage.CheckResetPasswordModalIsDisplayed())
{
modalFoundSuccess = true;
_loginPage.ClickCancelResetPasswordButton();
if (_loginPage.CheckResetPasswordModalIsDisplayed() != true)
{
modalFoundSuccess = false;
}
Assert.IsFalse(modalFoundSuccess, "The modal window did not close when the 'cancel' button was clicked on the modal pop up");
}
Assert.IsTrue(forgotPasswordControlFound, "Could not find the 'Forgotten Password' Modal box on the page");
}
Assert.IsTrue(forgotPasswordControlFound, "Was not able to find the 'Forgot Password' button on the '/login' page.");
}
Page Item
public class LoginPage : Page
{
private IWebDriver _driver;
public string userNameValidationText = "Username must be filled in.";
public string passwordValidationText = "Password must be filled in.";
public string incorrectLoginValidationText = "The user name or password is incorrect";
[FindsBy(How = How.ClassName, Using = "scfForm")]
private IWebElement _WFFMForm;
[FindsBy(How = How.XPath, Using = "//div[#class='scfSubmitButtonBorder']/input")]
private IWebElement _loginButton;
[FindsBy(How = How.XPath, Using = "//div[#class='scfSingleLineGeneralPanel']/input")]
private IWebElement _userNameField;
[FindsBy(How = How.XPath, Using = "//div[#class='scfPasswordGeneralPanel']/input")]
private IWebElement _passwordField;
[FindsBy(How = How.XPath, Using = "//div[#id='divForgotPassword']")]
private IWebElement _resetPasswordModal;
[FindsBy(How = How.XPath, Using = "//div[#id='divForgotPassword']/p/input")]
private IWebElement _forgotPasswordEmailInputField;
[FindsBy(How = How.XPath, Using = "//div[#id='divForgotPassword']/a[contains(., 'Reset My Password')]")]
private IWebElement _resetPasswordButton;
[FindsBy(How = How.XPath, Using = "//div[#id='divForgotPassword']/a[contains(., 'Cancel')]")]
private IWebElement _cancelResetPasswordButton;
[FindsBy(How = How.XPath, Using = "//div[#class='forgot-password']/a[contains(., 'Forgot Password')]")]
private IWebElement _forgotPasswordButton;
public LoginPage(IWebDriver driver)
: base(driver)
{
_driver = driver;
PageFactory.InitElements(_driver, this);
}
public void InputUserNameText(string phoneText)
{
_userNameField.Clear();
_userNameField.SendKeys(phoneText);
}
public void InputPasswordText(string queryText)
{
_passwordField.Clear();
_passwordField.SendKeys(queryText);
}
public void InputResetPasswordEmail(string resetEmail)
{
_forgotPasswordEmailInputField.Clear();
_forgotPasswordEmailInputField.SendKeys(resetEmail);
}
public void ClickLoginButton()
{
_loginButton.Click();
}
public void ClickResetButton()
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
wait.Until((d) => { return CheckModalHasLoaded(); });
_resetPasswordButton.Click();
}
public void ClickCancelResetPasswordButton()
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(20));
wait.Until((d) => { return CheckModalHasLoaded(); });
_cancelResetPasswordButton.Click();
}
public void ClickForgotPasswordButton()
{
_forgotPasswordButton.Click();
}
public void ClickLoginButtonForEmtpyValidation()
{
_loginButton.Click();
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
wait.Until((d) => { return CheckValidationTopBoxExists(); });
}
public bool CheckValidationForIncorrectLoginExists()
{
return Utility.IsThisElementPresent(_driver, By.XPath("//div[#class='scfSubmitSummary']/span"));
}
public bool loginFormExistsCheck()
{
return Utility.IsThisElementPresent(_driver, By.ClassName("scfForm"));
}
public bool CheckValidationTopBoxExists()
{
return Utility.IsThisElementPresent(_driver, By.ClassName("scfValidationSummary"));
}
public bool CheckResetPasswordModalIsDisplayed()
{
return Utility.IsThisElementPresent(_driver, By.XPath("//div[#id='divForgotPassword']"));
}
public bool CheckForgotPasswordControlExists()
{
return Utility.IsThisElementPresent(_driver, By.ClassName("forgot-password"));
}
public bool CheckModalHasLoaded()
{
return Utility.IsThisElementPresent(_driver, By.XPath("//div[#id='divForgotPassword']"));
}
}
If the modal is already in the DOM(ie. not loaded via ajax) you may need to change it to wait for element visible (assuming the modal is hidden). This is because the element is present always, just not visible. This explains why it works when you step through it in debug mode also.
Try using something like
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[#id='ElementYouWantToTarget']")));
to me this sounds like either your control lost focus or you did not focus onto right control.
What did you do to find the right control and then have focus on it ?

Categories

Resources