How to generate java fake objects quickly?

Simon Zhao
2 min readJan 30, 2021
Photo by Bermix Studio on Unsplash

Today I’d like to introduce a method to create or generate fake objects in java.

Sometimes, we want to test our apps with some randomly generated fake object, e.g. the Persons, Companies or CreditCards. They should have randomly generated names, IDs and emails. How to to this job?

Now we don’t have to write the whole program manually, we have [jfairy](https://github.com/Devskiller/jfairy) , it’s a fake data generator and you can use it to generate objects quickly.

Then what is jfairy?

Java fake data generator. Based on Wikipedia:

Fairyland, in folklore, is the fabulous land or abode of fairies or fays.

Now we create a java project with gradle like this:

plugins {
id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
implementation 'io.codearte.jfairy:jfairy:0.5.9'
implementation 'org.slf4j:slf4j-simple:1.7.30'
}

Then we generate random person objects as follows:

public static void main(String[] args) {
Fairy fairy = Fairy.create();
final Set<Person> persons = new SetOf<Person>(
fairy.person(),
fairy.person(),
fairy.person()
);
for(Person p:persons) {
log.info("p:"+p.getFirstName()+" "+p.getLastName()+" "+p.getUsername());
}
}

We get this result:

[main] INFO com.app1.Hello1 — p:Ellie Sweet esweet
[main] INFO com.app1.Hello1 — p:Isaiah Mcmahon isaiahm
[main] INFO com.app1.Hello1 — p:John Burks johnb

You can test JFairy online by navigating to (https://devskiller.com/datafairy/#/person)

It supports:

  • Personal details
  • Identity documents
  • Address and contact details
  • Banking information
  • Company information

I think it’s a great library, try it!

--

--

Simon Zhao

Security techie, developer, technology manager, software person and app-stuff doer..