Akif Tahir
Akif Tahir

Reputation: 171

Combine two selenium button clicks in an if statment

I want to combine the following two button actions into a SpecFlow scenario using an IF statement.

_driver.FindElement(By.Id("gbqfba")).Click(); // Google - 'Google Search'
_driver.FindElement(By.Id("gbqfsb")).Click(); // Google - 'I'm feeling lucky'

I want to use (.*) to pass either 'Google Search' or 'I'm feeling lucky'. Any ideas the best way to do this?

    [When("I click on (.*)")]
    public void WhenIClickOn(string buttonValue)
    {
    }

Upvotes: 1

Views: 243

Answers (1)

Sam Holder
Sam Holder

Reputation: 32944

A simple way would be to do this:

[When("I click on (.*)")]
public void WhenIClickOn(string buttonValue)
{
    if(buttonValue=="Google Search")
    {
         _driver.FindElement(By.Id("gbqfba")).Click(); // Google - 'Google Search'
    }
    else if(buttonValue=="I'm feeling lucky")
    {
         _driver.FindElement(By.Id("gbqfsb")).Click(); // Google - 'Google Search'
    }
    else
    {
        throw new ArgumentOutOfRangeException(); 
    }
}

but specflow also supports a better way of doing it by using a StepArgumentTransformation :

[When("I click on (.*)")]
public void WhenIClickOn(ButtonIdentifier buttonId)
{
    _driver.FindElement(By.Id(buttonId.Identifier)).Click(); 
}

[StepArgumentTransformation]
public ButtonIdentifier GetButtonIdentifier(string buttonValue)
{
     switch (buttonValue)
     {
          case "Google Search":
               return new ButtonIdentifier("gbqfba");
          case "I'm feeling lucky":
               return new ButtonIdentifier("gbqfsb");
          default:
               throw new ArgumentOutOfRangeException();          
     }
}

this ensures that your conversion from an id in the specification to an object which encapsulates that id and any related bits, happens in a single place and not in each test that uses it.

Upvotes: 1

Related Questions