Skip to content

Randomization parameters

Mahmoud Ben Hassine edited this page Jun 11, 2016 · 21 revisions

The EnhancedRandomBuilder is the main entry point to set all parameters of how Random Beans generate values:

EnhancedRandom random = EnhancedRandomBuilder.aNewEnhancedRandomBuilder()
   .maxCollectionSize(10)
   .maxStringLength(20)
   .charset(forName("UTF-8"))
   .dateRange(today, tomorrow)
   .timeRange(nine, five)
   .scanClasspathForConcreteTypes(true)
   .seed(123L)
   .build();

These parameters will be applied to all fields of the object graph.

Collection size

The maxCollectionSize parameter tells random beans to generate random collections with a bounded size.

String length

Setting the maxStringLength parameter tells random beans to generate random strings with a bounded size.

Setting the Charset parameter

You can use the charset parameter to tell random beans to generate random values from the specified Charset in all character-based fields, basically strings and characters. This parameter will be applied to all String and Character fields in the object graph.

Bounded Date and Time values

You can use the dateRange and timeRange parameters to generate bounded values for Date and Time fields.

Setting the seed parameter

The EnhancedRandom API can be configured with a seed option in order to generate the same random instances.

Using the same seed, each run will produce the same value. This feature is useful when you want stable random values across JVM restarts (in tests for instances).

Classpath Scanning

When the target object declares a field of an abstract or interface type, Random Beans will throw an ObjectGenerationException saying that it was unable to create a random instance of the abstract/interface type. The scanClasspathForConcreteTypes parameter tells Random Beans to scan the classpath and look for a concrete subtype of the abstract/interface field. Let's see a quick example:

abstract class Bar {}

class ConcreteBar extends Bar {}

class Foo {
   private Bar bar;
}

Let's try to generate a random instance of Foo:

EnhancedRandom enhancedRandom = EnhancedRandomBuilder.aNewEnhancedRandomBuilder()
   .scanClasspathForConcreteTypes(true)
   .build();
Foo foo = enhancedRandom.nextObject(Foo.class);

In the generated Foo instance, the bar field will be assigned a random instance of the ConcreteBar type. Without setting the scanClasspathForConcreteTypes parameter, Random Beans will throw an ObjectGenerationException

Clone this wiki locally