You may have come across file upload use case when working with WebDriver. File upload
is quite easy since it is same as typing in a text box but herein we need to pass path of file
to be uploaded. I used to keep a static file in src/test/resources folder of maven project and
would use it for upload operation. But you can also generate file during run time using
java.nio.file.Files class. Files class has createTempFile(java.lang.String, java.lang.String, java.nio.file.attribute.FileAttribute...) method which can be used to generate temporary files. For ex, you can generate a temporary pdf file and get back the File object as following -
File file = Files.createTempFile("test-" + accountNumber, ".pdf").toFile();
generatePDF(file, StringUtils.repeat("Dummy PDF", 10));
And this is how generatePDF looks -
public static File generatePDF(File file, String content) {
try {
Document e = new Document();
PdfWriter.getInstance(e, new FileOutputStream(file));
e.open();
e.add(new Paragraph(content));
e.close();
return file;
} catch (FileNotFoundException | DocumentException var3) {
throw new RuntimeException(var3);
}
}
Now you can get absolute path of file and pass it to upload text box -
getDriver.findElement(byLocator).sendKeys(file.getAbsolutePath());
Following this approach you don't have to keep a static file on my project.
So how do you handle file for file upload operation?