Micro Focus is now part of OpenText. Learn more >

You are here

You are here

The 5 best Apache Commons utilities for automation engineers

public://webform/writeforus/profile-pictures/corina-pip1.png
Corina Pip Senior QA Automation Consultant, NTT Data
 

Automation testers love to write code. Once they get the hang of it, they thoroughly enjoy writing as much of it as they can.

But developers take the opposite view. They enjoy writing as little code as possible, especially when it comes to certain bits that are more complex or that someone else has already been written. They don't like reinventing the wheel, so if someone has already written an open-source library or utility that does what they need and hundreds of users have vouched for its reliability, they figure it's faster, easier, and safer to use than the code that they write their own.

That's the mindset that testers need to embrace. It makes no sense to spend a lot of time writing code to process the data you feed into tests when you could be focusing on the tests and test logic.

Here are several situations where automation engineers can save time—and end up with better test code by using what's already available.

One of the best collections of reusable code

There are tons of open-source libraries out there that provide utilities and helpers you can use right out of the box. Generally speaking, whenever you're thinking about writing some code that processes data, someone probably has already written it and included it in a readily available library. Such processing might include:

  • Extracting strings out of other strings
  • Generating random strings
  • Extracting values from the database

You'll find one of the largest collections of Java-based helper classes and methods in the Apache Commons project. Everything is grouped by functionality into components such as:

  • Logging-related operations, under the Logging Component
  • Mathematics and statistics helpers, under the Math Component
  • Utilities for working with collections, under the Collection Component

There are hundreds of thousands of lines of code you can use in this repository. But here are my five favorite utilities classes, based on how useful they are in my day-to-day work.

StringUtils

Use the methods defined in this class for string operations such as joining, splitting, and replacement, with a lot of variations. The most interesting methods are:

substringBetween

FormatString substringBetween(final String str, final String open, final String close)

This lets you extract a substring from a given string by providing the delimiting strings.

ExampleStringUtils.substringBetween("https://techbeacon.com/", "//", "/");

Output: techbeacon.com

containsIgnoreCase

Formatboolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr)

Lets you check whether a string is a substring of another string while ignoring the case of both strings.

ExampleStringUtils.containsIgnoreCase("Maybe this little text contains", "this LITTLE text");

Output: true

swapCase

FormatString swapCase(final String str)

Switches the case of all the characters in a given string.

ExampleStringUtils.swapCase("Maybe this LITTLE text contains")

Output: mAYBE THIS little TEXT CONTAINS

RandomStringUtils

This class is useful for generating random strings, no matter if you want to have only letters or numbers or both in your resulting string, or you want to generate strings of random length each time you create them. Unfortunately, it's currently deprecated, but because the class is so easy to use, I still use it. Here are a few methods:

randomAlphanumeric

FormatString randomAlphanumeric(final int count)

Creates a string of a specified length that contains a mix of letters (both cases) and numbers.

Format: String randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive)

Creates a string of a length value between the values of the two specified parameters. Each time you run this, you get a string whose length you don't know from the start.

ExampleRandomStringUtils.randomAlphanumeric(20);

Output: xThThardCnhXGKNUOm5k

Creates a string of a length value between the values of the two specified parameters. Each time you run it you get a string whose length you don't know at the start.

ExampleRandomStringUtils.randomAlphanumeric(5, 15);

Output: jaMzU1eCSt

random

Formatrandom(final int count, final char... chars)

This method has several signatures, so you can use it to create strings in several ways. For example, here's how to create a string consisting of only characters you specified:

ExampleRandomStringUtils.random(10, 'a', 'b', 'c');

Output:  abaacaabcb

FileUtils

Thanks to FileUtils, working with files and folders has never been easier. With one line of code, you can create, move, copy, or delete files and folders, or read and write into or from files. You'll find several implementations for most of the methods in this class that fit more use cases.

writeLines

Formatvoid writeLines(File file, Collection<?> lines)

You can insert several lines into a file (which is created if it didn't already exist) by providing them as a list of strings. The initial file content gets overridden.

ExampleFileUtils.writeLines(new File("C:/folder/fileName.txt"), ImmutableList.of("1", "2", "3"));

copyFileToDirectory

Formatvoid copyFileToDirectory(File srcFile, File destDir)

You can copy an existing file to a destination folder easily.

ExampleFileUtils.copyFileToDirectory(new File("C:/locationOfFile/fileName.txt"), new File ("C:/destinationFolder"));

copyDirectoryToDirectory

Formatvoid copyDirectoryToDirectory(File srcDir, File destDir)

This is how you copy a folder to a destination folder.

ExampleFileUtils.copyDirectoryToDirectory(new File("C:/initialFolder"), new File ("C:/destinationFolder"));

DateUtils

This class has some useful methods for adding time periods to a date (from years to milliseconds), setting one of the date attributes to a specified value (again, from the year to the millisecond), or checking whether two Java date types are on the same day.

isSameDay

Formatboolean isSameDay(final Date date1, final Date date2)

This checks whether two dates are on the same day.

addYears

FormatDate addYears(final Date date, final int amount)

Returns a date object by adding the specified amount of years to the given date.

ExampleDateUtils.addYears(new Date(System.currentTimeMillis()), 1);

Output: Sat Nov 24 14:52:20 EET 2018

setDays

FormatsetDays(final Date date, final int amount)

Sets the value for the day in a date to the specified amount.

ExampleDateUtils.setDays(new Date(System.currentTimeMillis()), 1)

Output: Wed Nov 01 14:54:56 EET 2017

SystemUtils

If you need to perform actions that are dependent on the host operating system on which your tests run, use methods from SystemUtils to identify the operating system. This is useful if you run tests on remote machines that have disparate operating systems, and you need to do some setup based on the OS. You can use SystemUtils to check IS_OS_WINDOWS , or IS_OS_LINUX, or even IS_OS_WINDOWS_10.

A battle-tested collection of code for automation

For reference, you can find StringUtils, RandomStringUtils, DateUtils, and SystemUtils in the Lang component of Apache Commons. FileUtils is in the IO component.

The Apache Commons project is a good resource for optimizing the time you spend writing tests, as it lets you avoid writing helper code. This well-documented project is constantly releasing new features, so you're sure to find something that you can use in your automation efforts.

Want to learn more on this topic? Post your questions and comments below. Or, better yet, come watch my presentation, "Be productive in your automation with the Apache Commons helper libraries," at the 2018 Automation Guild online conference on January 8th.

Keep learning

Read more articles about: App Dev & TestingTesting