Useful: working with files and folders with FileUtils

When it comes to working with files (reading or writing their content, copying) or folders (copying their content, deleting them), the Apache FileUtils library offers a large number of methods for easily performing these tasks. Some of these are depicted below, together with their usage. For the full reference, check out this page: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html.

Importing the library into the project you are working on has to be done by importing the latest org.apache.commons.io package, in which FileUtils is included. The latest version ca be found here: http://commons.apache.org/proper/commons-io/.

Below the most useful of these methods are presented, described, and their usage is exemplified.

Working with files
  • writing to files:
    • writeStringToFile(File file, String data): write the string ‘data’ into the file ‘file’, by overwriting any content within the file, if it exists. If the file does not exist, it is created at this step. Usage: writeStringToFile(new File(“pathToFiles/firstFile.txt”), “Some text with writeStringToFile that overwrites file”);
    • writeStringToFile(File file, String data, Charset encoding, boolean append): write the string ‘data’ into the ‘file’ file. The string copied uses the encoding specified as the parameter in the method. Also, the string will be copied at the end of the file if ‘append’ is true(it will be appended to the existing file content, nothing will be erased), or it will erase all the file’s content – if ‘append’ is false. If the file does not exist, it is created at this step. Usage: writeStringToFile(new File(“pathToFiles/firstFile.txt”), “\nSome text with encodȊng, appended and with spacing\n”, Charset.defaultCharset(), true);
    • writeLines(File file, Collection<?> lines, boolean append): write into the specified file ‘file’, the items from the ‘lines’ collection, by appending them to the existing content (if ‘append’ is true) or by overwriting the existing content (if ‘append’ is false). The default separator between the items of the collection will be the new line (each item of the collection will appear on a new line in the file). Usage (writing a list of strings into the file, appending them to the existing content):         writeLines(new File(“pathToFiles/firstFile.txt”), listOfStrings, true); where listOfStrings is, for example: List<String> listOfStrings = ImmutableList.of(“Element 1”, “Element 2”, “Element 3”);
    • writeLines(File file, Collection<?> lines, String lineEnding, boolean append): write into the specified file ‘file’, the items from the ‘lines’ collection, by appending them to the existing content (if ‘append’ is true) or by overwriting the existing content (if ‘append’ is false). The separator between each item will be the one specified by the string parameter ‘lineEnding’. Usage: writeLines(new File(“pathToFiles/firstFile.txt”), listOfStrings, “|”, true); where listOfStrings is, for example: List<String> listOfStrings = ImmutableList.of(“Element 1”, “Element 2”, “Element 3”);
  • reading from files:
    • readFileToString(File file): read all the content from the ‘file’, keeping the new line separators (the ‘\n’ ones). Usage: String fileToString = readFileToString(new File(“pathToFiles/copyFile.txt”)); – where the string ‘fileToString’ will be assigned all the content of the file.
    • readLines(File file): read all the content from the file and place each separate line into an element of a string list. Usage:         List<String> fileToListOfStrings = readLines(new File(“pathToFiles/copyFile.txt”));
  • comparing two files:
    • contentEquals(File file1, File file2): returns true if two files have the same size and content. Usage: assertTrue(contentEquals(new File(“pathToFiles/firstFile.txt”), new File(“pathToFiles/copyFile.txt”)));
Working with folders
  • copying stuff:
    • copyFile(File src, File destination): copy the content of the ‘src’ file into the ‘destination’ file. If the latter does not exist, it will be created at this step. Usage:         copyFile(new File(“pathToFiles/firstFile.txt”), new File(“pathToFiles/copyFile.txt”));  –> ‘copyFile.txt’ will have identical content to ‘firstFile.text’
    • copyDirectory(File srcDir, File destinationDir): copy all the content from folder ‘srcDir’ directly under ‘destinationDir’. Usage:         copyDirectory(new File(“pathToFiles/randomFolder”), new File(“pathToFiles/Test”)); –>’randomFolder’ and ‘Test’ folder will have identical structure and content
    • copyFileToDirectory(File file, File destinationDir): copy the file ‘file’ to the file with the same name from the ‘destinationDir’ folder. If it does not exist, create a new file with the same name and put the content inside it. Usage:        copyFileToDirectory(new File(“pathToFiles/firstFile.txt”), new File(“pathToFiles/thirdOne”)); –> the ‘thirdOne’ folder will hold a ‘firstFile.txt’ file whose content is identical to the file from the ‘pathToFiles/firstFile.txt’ path
    • copyDirectoryToDirectory(File srcDir, File destinationDir): copies the content from the ‘srcDir’ folder into the folder with the same name from the ‘destinationDir’ folder, if it exists. Otherwise it creates the folder with the same name, and then replicates the content into the new folder. Usage:         copyDirectoryToDirectory(new File(“pathToFiles/thirdOne”), new File(“pathToFiles/4thOne”));
  • deleting folders
    • deleteDirectory(File srcDir): delete the ‘srcDir’ and all its’ content. Usage:  deleteDirectory(new File(“pathToFiles/Test”));
Example
List listOfStrings = ImmutableList.of("Element 1", "Element 2", "Element 3");
//overwrite content of existing file
writeStringToFile(new File("pathToFiles/firstFile.txt"), "Some text with writeStringToFile that overwrites file");
//append string to existing content, with specified encoding
writeStringToFile(new File("pathToFiles/firstFile.txt"), "\nSome text with encodȊng, appended and with spacing\n", Charset.defaultCharset(), true);
//append a list of strings to the file, each string ends with a new line character; if append=false, boolean parameter can be removed
writeLines(new File("pathToFiles/firstFile.txt"), listOfStrings, true);
//append a list of strings to the file, each string ends with a specified character (| in this case) ; if append=false, boolean parameter can be removed
writeLines(new File("pathToFiles/firstFile.txt"), listOfStrings, "|", true);
//check that the content of two files is identical
copyFile(new File("pathToFiles/firstFile.txt"), new File("pathToFiles/copyFile.txt"));
assertTrue(contentEquals(new File("pathToFiles/firstFile.txt"), new File("pathToFiles/copyFile.txt")));
//copy a file to within a directory
copyFileToDirectory(new File("pathToFiles/firstFile.txt"), new File("pathToFiles/thirdOne"));
//copies a directory's content to another directory
copyDirectory(new File("pathToFiles/thirdOne"), new File("pathToFiles/4thOne"));
//copy directory into a directory with the same name, within the destination directory
copyDirectoryToDirectory(new File("pathToFiles/thirdOne"), new File("pathToFiles/4thOne"));
//read content from a file into a String
String fileToString = readFileToString(new File("pathToFiles/firstFile.txt"));
System.out.println("File to string: " + fileToString);
//read content from a file into a List of Strings
List fileToListOfStrings = readLines(new File("pathToFiles/firstFile.txt"));
System.out.println(fileToListOfStrings.size());
for (int i=0; i<=fileToListOfStrings.size()-1; i++)
System.out.println("The list of strings: " + fileToListOfStrings.get(i));

The resulting structure, in the ‘pathToFiles’ location, is: the ‘firstFile.text’ and ‘copyFile.txt’ files, alongisde the ‘thirdOne’ folder whose content is a ‘firstFile.txt’ file, and a ‘4thOne’ folder, comprising of a ‘firstFile.txt’ file and a ‘thirdOne’ folder (this folder also containing a ‘firstFile.txt’ file). The content of the all the .txt files is identical, as it was copied from one to the other.

TestNG custom listeners: ITestListener


When running TestNG tests, one could want to perform some common actions – after each test has finished successfully, after each failed test, after each skipped test, or after all the tests have finished running, no matter their result. To apply such a common behavior to a group of tests, a custom listener can be created, that implements TestNG’s ITestListener interface. There are two types of methods to implement: a set of them are related to a single test’s run (onTestStart, onTestSuccess, onTestFailure, onTestSkipped, onTestFailedButWithinSuccessPercentage), the other to the whole suite’s run (onStart, onFinish). These methods, depending on their type, have a parameter passed to them: result, which is of type ITestResult – for the test run, and context, which is of type ITestContext, for the suite run. These types offer different information, for example: ITestResult can tell you when a test began to run, when it finished running, what status the test had (whether failed, passed), whereas ITestContext can tell you the list of all the passed tests, all the failed ones, and so on.

Continue reading TestNG custom listeners: ITestListener

Useful: generating random strings with RandomStringUtils

When writing tests that require the generation of random strings, a very useful class can come in handy, namely RandomStringUtils from the Apache Commons Langs utilities library. It can be used for generating string that contain only letters, only numbers, both, these and other characters. Continue reading Useful: generating random strings with RandomStringUtils

Running TestNG tests

Running TestNG tests can be done in two ways: either directly from the IDE (by selecting the desired tests and choosing to ‘Run TestNG tests’) or from the command line. The latter option is very useful when trying to run only a selection of all the tests, that might spread across different classes or packages, or to run tests that belong to certain groups. To do this, you need to create some .xml files that will select the tests that need to run and/or exclude tests not to run, add a configuration in the Maven profile created for running the tests, and run the proper Maven command. Continue reading Running TestNG tests

Waiting for UI events


When running Selenium tests, in many situations one would like to wait to for some event to take place, before performing an action. For example, after clicking a button, one would need to wait for an element to be displayed until the test can use that element (the element being displayed is the event, using it is the action). Continue reading Waiting for UI events

Run tests on multiple browsers

Running tests on multiple browsers helps ensure that the behavior and look of your application is consistent for all your users. Selenium offers the possibility to use most common browsers to run your tests against. However, if your application needs to run also on mobile devices, from within their browsers (not from within native applications that is), there is an easy way to simulate the mobile devices your users would open your website on. You can use Chrome ‘s user agent capabilities. Also, you can run tests on your regular browsers by having some extensions active in the browser session (you might need some additional actions to be performed with the help of these extensions). Continue reading Run tests on multiple browsers

%d bloggers like this: