Hiya Champs! Hope you had a great time taking screenshots and saving them locally. Today, let us see how we can create a word document and insert all images captured as part of a test case into that. Having a separate document for each test case would not only help us keep our workspace organized but also searching for a particular screenshot becomes a piece of cake. And the best part is, we are going to write code so that all this stuff happens automatically without any manual intervention.
Allow me to get straight to the point.
Step 1:
Download a couple JARs to make our jobs easier.
java2word-3.3.jar – Helps us to create a word document and manipulate it the way we want.
xstream-1.3.1.jar – Deals with images
Let us go ahead and download both these JAR files from https://code.google.com/archive/p/java2word/downloads (download location at the time of writing this article). I am placing these JARs in our GitHub repo as well, along with all other code files dealt as part of this post.
Step 2:
Add these JARs to our project build path.
We have seen this procedure numerous times before and hence I am not re-iterating it (Refer to Step 3 of this article for detailed explanation).
Step 3:
Create a class, “SaveDocument.java”.
Add the below code to the class file,
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.Document2004.Encoding;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Heading1;
import word.w2004.elements.Heading3;
import word.w2004.elements.Image;
import word.w2004.elements.Paragraph;
import word.w2004.style.HeadingStyle.Align;
public class SaveDocument {
public static void createDoc(String testCaseName, String[] imgFileNames) {
// Create a document object
IDocument myDoc = new Document2004();
myDoc.encoding(Encoding.UTF_8);
// Inserts one breakline
myDoc.addEle(BreakLine.times(1).create());
// Add client logo to document header
myDoc.getHeader().addEle(Image.from_FULL_LOCAL_PATHL("/Selenium/Logo.png")
.setHeight("30")
.setWidth("20")
.getContent());
// Add Project name to document header
myDoc.getHeader().addEle(Heading3.with(" ProjectName").withStyle().align(Align.RIGHT).create());
// Specify Test case name as document heading
myDoc.addEle(Heading1.with(testCaseName + " Test Case").withStyle().align(Align.CENTER).create());
myDoc.addEle(BreakLine.times(1).create());
// Add a description paragraph
myDoc.addEle(Paragraph
.with("Following are the related screenshots")
.create());
myDoc.addEle(BreakLine.times(1).create());
// Add company name to document footer
myDoc.getFooter().addEle(
Paragraph.with("@CompanyName").create());
// Loop through all the image files
for(String file:imgFileNames){
// Insert each image file to the document
myDoc.addEle(Image.from_FULL_LOCAL_PATHL(
"/Selenium/screenshots/" + file + ".png")
.setHeight("350")
.setWidth("500")
.getContent());
// Insert 2 linebreaks at the end of each inserted image
myDoc.addEle(BreakLine.times(2).create());
}
// Insert an image from web
myDoc.addEle(Image
.from_WEB_URL("http://www.google.com/images/logos/ps_logo2.png"));
// Create the word document specifying a location
File fileObj = new File("\\Selenium\\" + testCaseName + ".doc");
PrintWriter writer = null;
try {
writer = new PrintWriter(fileObj);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String myWord = myDoc.getContent();
writer.println(myWord);
writer.close();
// Print a confirmation image to console
System.out.println("Word document created successfully!");
}
}
Comments are provided for each line to make the code self-explanatory.
public static void createDoc(String testCaseName, String[] imgFileNames)
– This method has two arguments. First one is a String which specifies the test case name. This will be the name of the word document that will be created. The second argument is an array of all the screenshot names captured as part of that test case.
And in this method, we are creating a document object and performing operations such as,
- Adding headings, paragraphs
- Adding client logo and company name to the header
- Adding company name to the footer
- Inserting all the screenshots captured as part of a particular test case
- Inserting an image from the web (just to prove that this case is also possible)
- Saving the word document with the name of the test case in a particular location
Step 4:
A few modifications to ‘SaveScreenshot.java’ file.
A couple changes are made to the ‘SaveScreenshot.java’ class we created as part of the previous post.
- The function that generates a timestamp is removed and
- The file extension is changed from ‘.jpg’ to ‘.png’
The code now looks something like this,
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class SaveScreenshot {
public static void capture(String screenshotName, WebDriver driver) {
// Cast driver object to TakesScreenshot
TakesScreenshot screenshot = (TakesScreenshot) driver;
// Get the screenshot as an image File
File src = screenshot.getScreenshotAs(OutputType.FILE);
try {
// Specify the destination where the image will be saved
File dest = new File("\\Selenium\\screenshots\\" + screenshotName + ".png");
// Copy the screenshot to destination
FileUtils.copyFile(src, dest);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Sample Scenario
- Open Firefox browser.
- Navigate to google account creation page
- Locate first name text box by id
- Enter ‘fname01’ as the first name
- Take a screenshot and name it as “testCaseName” + “1”
- Locate last name text box by name
- Enter ‘lname01’ as the last name
- Take a screenshot and name it as “testCaseName” + “2”
- Create a word document in specified location and insert both these screenshots into it.
JUnit Code:
WordDocWithScreenshotTest.java class
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.blog.utilities.SaveDocument;
import com.blog.utilities.SaveScreenshot;
public class WordDocWithScreenshotTest {
//Declaring variables
private WebDriver driver;
private String baseUrl;
private String testCaseName = "WordDocWithScreenshot";
@Before
public void setUp() throws Exception{
// Selenium version 3 beta releases require system property set up
System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
+ "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
// Create a new instance for the class FirefoxDriver
// that implements WebDriver interface
driver = new FirefoxDriver();
// Implicit wait for 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// Assign the URL to be invoked to a String variable
baseUrl = "https://accounts.google.com/SignUp";
}
@Test
public void testPageTitle() throws Exception{
// Open baseUrl in Firefox browser window
driver.get(baseUrl);
// Locate First Name text box by id and
// assign it to a variable of type WebElement
WebElement firstName = driver.findElement(By.id("firstName"));
// Clear the default placeholder or any value present
firstName.clear();
// Enter/type the value to the text box
firstName.sendKeys("fname01");
//Take a screenshot
SaveScreenshot.capture(testCaseName + "1", driver);
// Locate last name text box by name
WebElement lastName = driver.findElement(By.name("lastName"));
// Clear and enter a value
lastName.clear();
lastName.sendKeys("lname01");
// Take a screenshot
SaveScreenshot.capture(testCaseName + "2", driver);
// Create a word document and include all screenshots
SaveDocument.createDoc(testCaseName, new String[]{testCaseName + "1",testCaseName + "2"});
}
@After
public void tearDown() throws Exception{
// Close the Firefox browser
driver.close();
}
}
The code is self-explanatory if comments are followed. Eclipse output is as below,
In Eclipse IDE, JUnit pane clearly shows that the test case ‘WordDocWithScreenshotTest.java’ has passed and the console has no errors. “Word document create successfully” is printed as expected.
As specified in the code, the screenshots are saved to “E:/Selenium/screenshots” path with the names in the mentioned format.
The word document is created and saved in the specified location as well, “E:/Selenium/”. The document looks as follows,
Created word document, all code files, and JARs are placed in the GitHub repo for easy access. You can star and fork the repository for convenience. Please go through the ‘README.md’ file for clear instructions.
Happy coding! Have a nice day!
saving all the screenshots in one document how to write code pls help out
Thank You! CHANDANA CHAITANYA. The problem resolved. It really helped. Thank You
Perfect! Happy learning Shweta 🙂
Hi Lakshmi Chandana,
It is really a useful topic and this is what I was looking for my project. Thanks for sharing this.
I am able to do everything as mentioned and I have created doc file also. once execution done i opened the doc file but screen shot not added I’m getting an error in the doc file as “The linked image cannot be displayed. The file may have been moved, renamed or deleted. Verify that the link points to the correct file and location”.
This is the same issue which is reported by Manova above. Can you please help me.
Hi Suhani,
Thank you. Regarding the error, it can be something to do with the path where the image file is getting saved and the path you are referring to in the code for inserting that image in the document.
Step 1: Check if the screenshot is getting created successfully in the mentioned path.
In my code this is the line from “SaveScreenshot.java”:
// Specify the destination where the image will be saved
File dest = new File(“\\Selenium\\screenshots\\” + testCaseName + “_” + timestamp() + “.jpg”);
Step 2: If the screenshot is saved successfully in the path you have mentioned, check if you are giving the same path while trying to insert it in the document.
In my code this is the line from “SaveDocument.java”:
// Insert each image file to the document
myDoc.addEle(Image.from_FULL_LOCAL_PATHL(
“/Selenium/screenshots/” + file + “.jpg”)
.setHeight(“350”)
.setWidth(“500”)
.getContent());
Make sure the file extensions such as, ‘.jpg’ or ‘.png’ are mentioned properly in both paths. This might also be a reason why you are getting that error.
even after writting same path still showing same above mentioned errors
yes, i’m also getting same error message after provide same extension on both path. could you help on this Issue?
i have updated my email. please reply to this mail id.
Thanks
Manova
Sure Manova.
Can you please suggest the same solution as I am also facing same issue.
Hi Shweta,
Please check if you are mentioning the file extensions properly in your code. I have explained this in detail to Suhani’s comment. Let me know the results and we can debug further.
Hi Lakshmi Chandana,
Really an useful topic and this is what i was looking for my project. Thanks for sharing this.
i am able to do everything as mentioned and i have creaeted doc file also. once execution done i opened the doc file but screen shot not added im getting an error in the doc file as “The linked image cannot be displayed. The file may have been moved, renamed or deleted. Verify that the link points to the correct file and location”
Thanks. I have replied to your email id as requested.