Skip to content
Mahmoud Ben Hassine edited this page Feb 19, 2016 · 19 revisions

Introduction

Testing applications against random input, also known as Monkey Tests 🐵, is an essential step to improve stability and robustness.

There are many use cases where one may need to generate random data during tests such as:

  • Populating a test database with random data
  • Generating random input file for a batch application
  • Generating random model to test view rendering in a MVC web application
  • Generating random form input to test form validation
  • etc

Generating random data is a tedious task, especially when the domain model involves many related classes. This is where Random Beans comes to play, to help you populating your domain objects easily with random data.

Let's see a quick example, suppose you have the following classes:

With Random Beans, generating a random Person object can be done like this:

EnhancedRandom enhancedRandom = new EnhancedRandomBuilder().build();
Person person = enhancedRandom.nextObject(Person.class);

The library will recursively populate all the object graph. Without Random Beans, you would write something like:

Street street = new Street(12, (byte) 1, "Oxford street");
Address address = new Address(street, "123456", "London", "United Kingdom");
Person person = new Person("Foo", "Bar", "foo.bar@gmail.com", Gender.MALE, address);

And if these classes do not provide constructors with parameters (may be some legacy beans you don't have the control over), you would write:

Street street = new Street();
street.setNumber(12);
street.setType((byte) 1);
street.setName("Oxford street");

Address address = new Address();
address.setStreet(street);
address.setZipCode("123456");
address.setCity("London");
address.setCountry("United Kingdom");

Person person = new Person();
person.setFirstName("Foo");
person.setLastName("Bar");
person.setEmail("foo.bar@gmail.com");
person.setGender(Gender.MALE);
person.setAddress(address);

As you can see, Random Beans can tremendously reduce the code of generating random test data than doing it by hand.