In many of the test scenarios, we need to download file to test that file download features are working or not. At the time of writing automated script on file download we have to interact with the web element as well as browser file download dialog. Our Selenium WebDriver API can only works on clicking the button to display the File download dialog but cannot interact with the file dialog. In this situation we need to use the power of C#.
.Net has a library to handle file upload dialog. It has a SendKeys class that has a method SendWait(string keys). It sends the given key on the active application and waits for the message to be processed. It does not return any value.
Common syntax to use this command,
SendKeys.SendWait(string keys);
Here keys is the string of keystrokes.
For example in C#,
SendKeys.SendWait() takes a string like “{Enter}” that it executes the enter key from keyboard. When File download dialog is displayed, OK button is activated by default. At this time if we press enter key from keyboard it executes the OK command.
Note that we need to add System.Windows.Forms namespace to get this method.
Lets do a short project on how we can implement in our test scenario. For example we have the following page where we have to download a file by clicking download link.
Page link : http://sample-videos.com/
Step 1 : Open Visual Studio and create a new project with Console Application type.
Step 2 : Add a reference for Webdriver from Nuget package manager. How to add a reference from Nuget package can be found in my another post.
Step 3 : Write the following code for opening page using Firefox Browser under static void Main(string[] args) method.
Note that we need to add following namespaces for webdriver.
Step 4 : Write the code for clicking on Download link of the page to open file download dialog.
Step 5 : Write the code to handle file upload dialog to click OK button.
Note that we need to add the following namespace SendKeys.SendWait().
We will not get this namespace if we do not add “System.Windows.Forms” reference from Reference manager window. We get this reference by right clicking on Reference and click on Add Reference option.
Reference section will be,
Note : Sometimes we need to add Thread.Sleep(30) method before SendKeys.SendWait() method to activate the OK button. We have to add System.Threading namespace to implement this statement.
Step 6 : Now close the driver. Main method will be,
Step 7 : Run the application by clicking on Start button. It opens the browser and download file using SendKeys.SendWait() methods.
Happy scripting with Selenium Webdriver using the power of C#.
No comments:
Post a Comment