Easy Random Documentation

repository·main·Indexed 23 days ago

https://github.com/j-easy/easy-random

A Java library for generating random objects and populating complex object graphs to simplify test data preparation. It features the EasyRandomParameters class for configuration, the Randomizer interface for customization, and field/type exclusion via predicates. Available extensions include support for JUnit, Vavr, and Protocol Buffers.

Tokens
736
Snippets
3
Records
4
Agent score
32%

What's inside Easy Random

  1. Available Easy Random extensions

    main

    The following extensions are available to expand the capabilities of Easy Random:

    • JUnit extension: Use Easy Random to generate random data directly in JUnit tests.
    • Vavr extension: Adds support for randomizing Vavr types.
    • Protocol Buffers extension: Adds support for randomizing Protocol Buffers generated types.
  2. Generate random Java objects with EasyRandom

    main

    Easy Random is a library designed to generate random Java objects, acting as an ObjectMother for the JVM. It can recursively populate an entire object graph for any given type using the nextObject(Class type) method.

    EasyRandom easyRandom = new EasyRandom();
    Person person = easyRandom.nextObject(Person.class);
  3. Configure EasyRandom using EasyRandomParameters

    main

    To control how random data is generated, use the EasyRandomParameters class. This allows you to configure various constraints such as seeds, object pool size, randomization depth, and specific ranges for strings, dates, and collections.

    EasyRandomParameters parameters = new EasyRandomParameters()
       .seed(123L)
       .objectPoolSize(100)
       .randomizationDepth(3)
       .charset(forName("UTF-8"))
       .timeRange(nine, five)
       .dateRange(today, tomorrow)
       .stringLengthRange(5, 50)
       .collectionSizeRange(1, 10)
       .scanClasspathForConcreteTypes(true)
       .overrideDefaultInitialization(false)
       .ignoreRandomizationErrors(true);
    
    EasyRandom easyRandom = new EasyRandom(parameters);
  4. Customize randomization and exclude fields

    main

    You can customize the generation of specific types using the Randomizer interface and exclude specific fields from the object graph using predicates.

    To exclude fields, use the static methods named, ofType, and inClass from org.jeasy.random.FieldPredicates. You can also use TypePredicates to exclude entire types.

    EasyRandomParameters parameters = new EasyRandomParameters()
       .randomize(String.class, () -> "foo")
       .excludeField(named("age").and(ofType(Integer.class)).and(inClass(Person.class)));
    
    EasyRandom easyRandom = new EasyRandom(parameters);
    Person person = easyRandom.nextObject(Person.class);