user728779
user728779

Reputation: 1

IWebElement object needs to be created each time to find a new element on a page?

IWebElement abc = driver.FindElement(By.Id("txtUserName"));
abc.SendKeys("TEST");
IWebElement abc1 = driver.FindElement(By.Id("txtPassword"));
abc1.SendKeys("TEST123");
IWebElement abc2 = driver.FindElement(By.Id("buttonSignIn"));
abc2.Click();

Do we need to explicitly create a new object each time to find an element on the same page?

Can we just create an IWebElement once? Like it was with Selenium 1?

selenium.type("TEST");
selenium.click();

Upvotes: 0

Views: 5307

Answers (2)

CBRRacer
CBRRacer

Reputation: 4659

No you don't need to create a new object every time but you would need to use selenium to catch the object for each new object you want to interact with. Also if you click to a new page and then click back any elements that you have will throw a stale element reference exception that would need to be handled. All you really need to do to Instantiate the element is this:

private IWebElement element;

private void Method()
{
  element = driver.FindElement(By.Id("txtUserName"));
  element.Clear();
  element.SendKeys("TEST");

  element = driver.FindElement(By.Id("txtPassword"));
  element.Clear();
  element.SendKeys("Test123");

  element = driver.FindElement(By.Id("buttonSignIn"));
  element.Click();
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502406

What makes you think that's creating a new object?

It's declaring a new variable, but that's not the same thing... and it's very important to understand the difference between them.

I can't see any reason why you couldn't reuse a single variable if you wanted to... but I'd personally try to use different variable names to represent the different elements I was finding:

IWebElement usernameInput = driver.FindElement(By.Id("txtUserName"));
usernameInput.SendKeys("TEST");

IWebElement passwordInput = driver.FindElement(By.Id("txtPassword"));
passwordInput.SendKeys("TEST123");

IWebElement signinButton = driver.FindElement(By.Id("buttonSignIn"));
signinButton.Click();

That makes it clearer what action I'm trying to take, IMO. Of course, if you're using the "find an element, send it some keys" pattern regularly, you might want to write a convenience method, so you could call:

EnterText("txtUserName", "TEST");
EnterText("txtPassword", "TEST123");
SubmitForm("buttonSignIn");

Upvotes: 1

Related Questions