Generate random data in Java using Java Faker

Last Updated:  June 14, 2020 | Published: July 20, 2019

Once your new prototype is ready for a first demo, you usually need some data to present. If you already have a solid data source this should be no problem, but what about the opposite case? How to simply create meaningful random data for your Java application?

In the past, I've only used the UUID and ThreadLocalRandom  Java classes to create random data. As these are really limited and don't offer domain-specific random data I searched for a better solution. While searching I found the Faker gem for Ruby and luckily a Java port of it: Java Faker. With this easy-to-use library, you have access to many domains and can generate meaningful random data in seconds.

Getting started with Java Faker

You can include Java Faker in your Maven project with the following dependency:

To start using random data, just create an instance of the Faker class:

You don't have to create a Faker instance whenever you need random data as the methods randomly access the underlying data. Java Faker uses .yml files in /src/main/resources to retrieve its data.

With this library, you have access to more than 30 different domains and can create random data for nearly every use case.  You can generate random data for a specific domain using the fluent API:

These domains include:

  • Finance
  • Food
  • Books
  • Name
  • Address
  • Business

and also funny domains like:

  • Yoda
  • ChuckNorris
  • HarryPotter
  • LordOfTheRings

To get a list of all available Fakers (domains), have a look at the README.md of the project.

A simple use case for Java Faker

To demonstrate an example usage of Java Faker I'm using a REST API to return random persons, books, and food.  For this example, Spring Boot 2.3 and Java 11 are used, but any other Java setup would also work.

The sample application offers different endpoints to get random data:

Return localized random data

The default locale for the random data is EN. In addition, the libraries offer the capability to return localized random data. If you specify your locale, make sure it's supported and have a look at the corresponding .yml file to check if someones translated the English examples.

If there is no translation for your locale for e.g. beers, the library will fallback to English.

The locale is specified as a constructor argument of the Faker class:

This object instance is now capable of returning random data in German:

Or any other locale which is listed in the README.md of the project:

You can find the source code for this example on GitHub.

Have fun creating random data with Java Faker,

Phil

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>