top of page

Easily compare a list of Strings with the contents of a file

Context: you need to check that the values you have in a List of Strings are the same as the contents of a file. An element in the List will correspond to an entire line from the file. How can you achieve this easily?

Well, first, let’s see what the data to compare is. Let’s go with an example, and assume that your List of Strings contains the following values: “apples”, ”pears”, ”cherries”, ”peaches”, ”plums”. The file that you need to compare the List to has the following structure:


You can easily see that the contents of the List and the contents of the file are the same, as they all contain the same names of some very much-loved fruit. Testing this can be done in several ways of course, but below you will find a suggestion using the FileUtils class from the Apache Commons library. Specifically, we will use the ‘readLines’ method from this class.

Writing the test that will check the equality of the two will start with the import of the ‘readLines’, which I will do as a static import, so I can shorten the call to the method from the test:

import static;

Let us assume the name of the List of Strings is ‘fruitList’. I will not go over how you create a List of Strings. Also, let’s assume that the path of the file containing the fruit names is ‘filePath’. I will not go over how the fruit names were added to the file either. The comparison between the List and the contents of the file (remember, we are checking an element of the list to a line of the file, based on position – first element with first line, second element with second line, etc.), will be done using an ‘assertEquals’, as follows:

assertEquals(readLines(new File(“filePath”)), fruitList);

The ‘readLines’ method returns a List of Strings, so the comparison will be done, in fact, between two Lists. Hence, the order is also checked to be the same, when using assertEquals (the order of the elements in the List needs to be the same as the order of the lines in the file, for the assertEquals to return true).

Recent Posts

See All

Creating an Architecture for Your Automated Tests Writing Automated Tests in Small Increments 4 Times Your Automation Passed While Bugs Were Present Now That You’ve Created Automated Tests, Run Them!

This week my newest article was released, this time on how to use Log4j to log relevant test automation information:

bottom of page