Total Pageviews

Monday 25 November 2013

Selenium WebDriver: Perform a drag and drop

If your browser supports advanced user interactions like drag and drop, you can use the Actions class to imitate this behaviour.

Drag and Drop

This is an interactive demo. Drag and drop the small square into the large square. 



Below you will find an example detailing how to drag one element to another:

[C#] Solution 1

  [Test]
  public void draganddrop()
  {
   driver.Navigate().GoToUrl("http://testautomationengineer.blogspot.com/2013/11/selenium-webdriver-perform-drag-and-drop.html");
   
   IWebElement source = driver.FindElement(By.Id("draggable"));
   IWebElement target = driver.FindElement(By.Id("droppable"));
   
   Actions builder = new Actions(driver);
    builder.DragAndDrop(source, target);
    builder.Build().Perform();

    Assert.That(dragAndDropIsComplete());
  }
  
  private bool dragAndDropIsComplete()
  {
   return driver.FindElement(By.ClassName("drag-and-drop-complete")).Displayed;
  }

[C#] Solution 2


  [Test]
  public void draganddrop()
  {
   driver.Navigate().GoToUrl("http://testautomationengineer.blogspot.com/2013/11/selenium-webdriver-perform-drag-and-drop.html");
   
   IWebElement source = driver.FindElement(By.Id("draggable"));
   IWebElement target = driver.FindElement(By.Id("droppable"));
   
   Actions builder = new Actions(driver);
          builder.ClickAndHold(source);
          builder.MoveToElement(target);
          builder.Release(target);
          builder.Build().Perform();
    
   Assert.That(dragAndDropIsComplete());
  }
  
  private bool dragAndDropIsComplete()
  {
   return driver.FindElement(By.ClassName("drag-and-drop-complete")).Displayed;
  }

Tips:

  • Ensure native events are enabled
  • Maximise your browser windows before you perform a drag and drop


Reference: 

DragAndDrop

Performs a drag-and-drop operation from one element to another.

ClickAndHold

Clicks and holds the mouse button down on the specified element.

MoveToElement

Moves the mouse to the specified element.

No comments:

Post a Comment