Sunday 29 October 2017

Uploading file with the help of Robot class in Selenium Automation

While implementing automation, we always come across with a situation where our code need to upload a file using our selenium code.

As we know Selenium is a Web Automation tool and which don't support windows automation. In order to upload a files, we have to perform some Windows based operations.

There are different ways to achieve this. One of the way is to take the support of Robot and StringSelection class.

Below simple code will help to perform file upload as part of Selenium Automation:

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FileUpload {

public static void main(String[] args) throws InterruptedException, AWTException {

// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://html.com/input-type-file/");

                // Absolute path of the file need to uploaded
String fileLocation = "C:\\Users\\testData.xlsx";

                // the code which helps us to perform Copy and Paste options from Clipboard
StringSelection stringSelection = new StringSelection(fileLocation);

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
                driver.findElement(By.id("fileupload")).click();
// CTRL+V and ENTER keys are the keyboard events to achieve the Keyboard operations
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);

Thread.sleep(5000);
driver.quit();
}
}

Monday 9 October 2017

Reading a file as String

Sometimes we need to read test input from a file(.txt/.xml etc) and enter into a text area field. Below code will help to read the content of file and stored in a string.

To achieve this we need to take the help of Apache CommonsIO. This will be available at Apache CommonsIO and download  zip file

Extract the zip file and you will find commons-io-2.5.jar file

Add the jar file to the project 

import java.io.File;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;

public class ReadFileToString {
public static void main(String[] args){
File inputFile = new File("d://test.xml");
//location of the tile
try {
               //Reading file to string
String str = FileUtils.readFileToString(inputFile,Charset.forName("utf-8"));
   System.out.println(str);
} catch (Exception e) {
    e.printStackTrace();
}
}
}

With the help of above code, we can have the content of file. Now we can use the variable to enter the text in text area input field.

In this case, 

driver.findElement(By.id("TextArea")).sendKeys(str);