Code Monkey home page Code Monkey logo

easy-random's Introduction


Easy Random
The simple, stupid random Java™ beans generator

MIT license Build Status Maven Central Javadocs Project status


Project status

Active

Latest news

  • 1/15/2024 7.0.0 Major release, default Java version bumped to 17 and other 3PP version bump. [Breaking changes].
  • 9/1/2023 6.2.1 Minor release to initialize leaf nodes for Records [Breaking change].
  • 8/10/2023 6.2.0 Minor release to add custom radomizer support for protobuf, 3PP and code refactoring.
  • 5/23/2023 6.1.8 Patch release to fix #26 and #28, thanks @carborgar.
  • 5/12/2023 6.1.7 Patch release to improve record support, thanks @mjureczko and minor 3PP fixes.
  • 3/19/2023 6.1.5 Patch release to bump protobuf-java and snakeyaml and fix bug preventing custom randomizers on Record Types. Thanks carborgar
  • 3/12/2023 6.1.3 Patch release to fix bug preventing Collections field population
  • 10/29/2022 6.1.2 Patch release to bump protobuf version to vulnerability
  • 9/23/2022 6.1.1 Added support to generate random protobuf data, this is based on murdos/easy-random-protobuf
  • 8/10/2022 Added a fork with JDK 11 support easy-random-jdk11 package is available in maven centeral.
  • 8/3/2022: Added support to JDK 16 and Java Record and minor bug fixes
  • 15/11/2020: Easy Random v5.0.0 is out and is now based on Java 11. Feature wise, this release is the same as v4.3.0. Please check the release notes for more details.
  • 07/11/2020: Easy Random v4.3.0 is now released with support for generic types and fluent setters! You can find all details in the change log.

What is Easy Random ?

Easy Random is a library that generates random Java beans. You can think of it as an ObjectMother for the JVM. Let's say you have a class Person and you want to generate a random instance of it, here we go:

EasyRandom easyRandom = new EasyRandom();
Person person = easyRandom.nextObject(Person.class);

The method EasyRandom#nextObject is able to generate random instances of any given type.

What is this EasyRandom API ?

The java.util.Random API provides 7 methods to generate random data: nextInt(), nextLong(), nextDouble(), nextFloat(), nextBytes(), nextBoolean() and nextGaussian(). What if you need to generate a random String? Or say a random instance of your domain object? Easy Random provides the EasyRandom API that extends java.util.Random with a method called nextObject(Class type). This method is able to generate a random instance of any arbitrary Java bean.

The EasyRandomParameters class is the main entry point to configure EasyRandom instances. It allows you to set all parameters to control how random data is generated:

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);

For more details about these parameters, please refer to the configuration parameters section.

In most cases, default options are enough and you can use the default constructor of EasyRandom.

Easy Random allows you to control how to generate random data through the org.jeasy.random.api.Randomizer interface and makes it easy to exclude some fields from the object graph using a java.util.function.Predicate:

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);

In the previous example, Easy Random will:

  • Set all fields of type String to foo (using the Randomizer defined as a lambda expression)
  • Exclude the field named age of type Integer in class Person.

The static methods named, ofType and inClass are defined in org.jeasy.random.FieldPredicates which provides common predicates you can use in combination to define exactly which fields to exclude. A similar class called TypePredicates can be used to define which types to exclude from the object graph. You can of course use your own java.util.function.Predicate in combination with those predefined predicates.

#Easy Random for Protobuf easy-random-protobuf module provides support for generating random data for protobuf message objects. For full support for easy-random capabilities it is advised to rely on

ProtoEasyRandom easyRanom  = new ProtoEasyRandom();

Why Easy Random ?

Populating a Java object with random data can look easy at first glance, unless your domain model involves many related classes. In the previous example, let's suppose the Person type is defined as follows:

Without Easy Random, you would write the following code in order to create an instance of the Person class:

Street street = new Street(12, (byte) 1, "Oxford street");
Address address = new Address(street, "123456", "London", "United Kingdom");
Person person = new Person("Foo", "Bar", "[email protected]", Gender.MALE, address);

And if these classes do not provide constructors with parameters (may be some legacy beans you can't change), 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("[email protected]");
person.setGender(Gender.MALE);
person.setAddress(address);

With Easy Random, generating a random Person object is done with new EasyRandom().nextObject(Person.class). The library will recursively populate all the object graph. That's a big difference!

How can this be useful ?

Sometimes, the test fixture does not really matter to the test logic. For example, if we want to test the result of a new sorting algorithm, we can generate random input data and assert the output is sorted, regardless of the data itself:

@org.junit.Test
public void testSortAlgorithm() {

   // Given
   int[] ints = easyRandom.nextObject(int[].class);

   // When
   int[] sortedInts = myAwesomeSortAlgo.sort(ints);

   // Then
   assertThat(sortedInts).isSorted(); // fake assertion

}

Another example is testing the persistence of a domain object, we can generate a random domain object, persist it and assert the database contains the same values:

@org.junit.Test
public void testPersistPerson() throws Exception {
   // Given
   Person person = easyRandom.nextObject(Person.class);

   // When
   personDao.persist(person);

   // Then
   assertThat("person_table").column("name").value().isEqualTo(person.getName()); // assretj db
}

There are many other uses cases where Easy Random can be useful, you can find a non exhaustive list in the wiki.

Extensions

Articles and blog posts

Who is using Easy Random ?

Contribution

You are welcome to contribute to the project with pull requests on GitHub. Please note that Easy Random is in maintenance mode, which means only pull requests for bug fixes will be considered.

If you believe you found a bug or have any question, please use the issue tracker.

Core team and contributors

Core team

Awesome contributors

Thank you all for your contributions!

License

The MIT License. See LICENSE.txt.

easy-random's People

Contributors

arnzel avatar carborgar avatar dadiyang avatar dvgaba avatar dziga avatar feckertson avatar fmbenhassine avatar frankowskid avatar georgekankava avatar gitter-badger avatar huningd avatar jin-harmoney avatar kermit-the-frog avatar lejeanbono avatar lucasandersson avatar lutovich avatar mjureczko avatar pascalschumacher avatar petromir avatar prietopa avatar reitzmichnicht avatar rmcquary avatar rodriguealcazar avatar sansherbina avatar seregamorph avatar svcacct-epo-cicd avatar toilal avatar unconditional avatar valters avatar xcorail avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

easy-random's Issues

easyRandom.objects always returning the same record list

Hi,

Just found a bug regarding records. When you randomize a list of records, it's always returning the same value, so all the objects inside the stream are the same (see attached test). I opened the issue just in case someone is facing the same and can provide a workaround or guidelines to fix it.

This is the test I made:

    @Test
    void typeRecordListShouldBePopulatedWithDifferentValues() {
        List<TestRecord> recordList = easyRandom.objects(TestRecord.class, 2).toList();

        TestRecord rnd1 = recordList.get(0);
        TestRecord rnd2 = recordList.get(1);

        assertThat(rnd1).isNotEqualTo(rnd2);

    }

Found it using version 6.1.7

Copyright infringement: Please remove easy-random-protobuf

Protobuf randomizer not using custom randomizers

hi,
I just noticed that protobuf field predicates are not working when specifying custom random values providers.

For example, the following test fails

    void shouldUseCustomProviderRegistryToFillFields(){
        EasyRandomParameters parameters = new EasyRandomParameters().randomize(ProtobufPredicates.named("int32Field"), () -> 42);
        EasyRandom easyRandom = new EasyRandom(parameters);

        Proto3Message protoInstance = easyRandom.nextObject(Proto3Message.class);

        assertThat(protoInstance.getInt32Field()).isEqualTo(42);
    }

I've found a solution and pushed it to my fork, will create PR now because it involves exposing EasyRandomParameters's custom randomizer provider so that we are able to access it. Any suggestion is welcome.

Record fields still being generated even if randomizer is specified for field to set it to null

Given a record like:

public record MyRecord(String fieldOne, AnotherRecord fieldTwo) {}

where AnotherRecord is a record

When I do:

easyRandomParameters.randomize(
            field -> field.equals(fieldTwoField), () -> null
        );

I would expect the value for fieldTwo to be null. This works with most primitives & other classes that are not records. However, with records, fieldTwo is not null and still subject to value generation.

I've sort of worked around this by also adding:

easyRandomParameters.randomize(AnotherRecord.class, new SkipRandomizer());

however if in my object I have more than one field that is AnotherRecord, ie:

public record SomeOtherRecord(AnotherRecord fieldOne, AnotherRecord fieldTwo) {}

naturally both fieldOne & fieldTwo would be skipped, so it doesn't work in those scenarios. The intention is just to null out that single field (fieldTwo).

[Feature] New module to support generate salesforce entities generation

Thank you for taking time to open this issue! Please check the known limitations section before opening an issue.

Please provide as much context as possible to help us fixing the issue (at least easy-random version you are using).

  • If you are reporting a bug, the best way is to provide a failing test.
  • If you are requesting a feature, don't hesitate to explain in detail your suggestion with code examples.
  • If you have a question, please first check if there is no (closed) issue about it. You may ask your question on the Gitter channel of the project.

Many thanks upfront!

Better jitpack.io support

jitpack runs your build with Java 8

Easy fix

jitpack.yml

jdk:
  - openjdk17
install:
  - mvn install -Dmaven.javadoc.skip=true -DskipTests

Version 6.1.8 does not initialize collections at the end of nesting data structures

There is a test that is supposed to verify the scenario, i.e. shouldLimitTheNestingLevel_whenInRecursiveStructures, but it was changed from:

        assertThat(actual.children().get(0))
            .as("On the 2nd level, the field should be initialized with empty list, i.e. end of nesting.")
            .isEqualTo(new NestedRecordThroughCollection(List.of()));

to:

        assertThat(actual.children().get(0))
            .as("On the 2nd level, the field should be initialized with empty list, i.e. end of nesting.")
            .isEqualTo(new NestedRecordThroughCollection(null));

When reverting the test, it fails as the list 'in children' is not initialized.

Randomization parameters are not used for records

When trying to generate random record, it seems that EasyRandomParameters are not used for generation.
Example:

import org.jeasy.random.EasyRandom;
import org.jeasy.random.EasyRandomParameters;
import org.jeasy.random.randomizers.text.StringRandomizer;
import org.junit.jupiter.api.Test;

import static org.jeasy.random.FieldPredicates.named;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class TestParameters {

    private final EasyRandom easyRandom = new EasyRandom(new EasyRandomParameters()
        .randomize(named("name"), new StringRandomizer(1))
    );

    @Test
    void test() {
        var result = easyRandom.nextObject(TestRecord.class);
        assertEquals(1, result.name().length());
    }

    record TestRecord(
        String name,
        String phone
    ){}
}

Result:

Expected :1
Actual   :23

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.