Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The simple, stupid random Java beans/records generator

License

MIT, MIT licenses found

Licenses found

MIT
LICENSE.txt
MIT
licence-header-template.txt
NotificationsYou must be signed in to change notification settings

j-easy/easy-random

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1,251 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


Easy Random
The simple, stupid random Java™ objects generator

MIT licenseBuild StatusMaven CentralJavadocsProject status


Project status

As of November 15, 2020, Easy Random is in maintenance mode. This means only bug fixes will be addressed from now on (exceptforrecords support which will be released when Java 16 is out).Version 5.0.x (based on Java 11) and version 4.3.x (based on Java 8) are the only supported versionsfor now. Please consider upgrading to one of these versions at your earliest convenience.

Latest news

  • 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 therelease 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 thechange log.

What is Easy Random ?

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

EasyRandomeasyRandom =newEasyRandom();Personperson =easyRandom.nextObject(Person.class);

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

What is this EasyRandom API ?

Thejava.util.Random API provides 7 methods to generate random data:nextInt(),nextLong(),nextDouble(),nextFloat(),nextBytes(),nextBoolean() andnextGaussian().What if you need to generate a randomString? Or say a random instance of your domain object?Easy Random provides theEasyRandom API that extendsjava.util.Random with a method callednextObject(Class type).This method is able to generate a random instance of any arbitrary Java bean.

TheEasyRandomParameters class is the main entry point to configureEasyRandom instances. It allows you to set allparameters to control how random data is generated:

EasyRandomParametersparameters =newEasyRandomParameters()   .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);EasyRandomeasyRandom =newEasyRandom(parameters);

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

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

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

EasyRandomParametersparameters =newEasyRandomParameters()   .randomize(String.class, () ->"foo")   .excludeField(named("age").and(ofType(Integer.class)).and(inClass(Person.class)));EasyRandomeasyRandom =newEasyRandom(parameters);Personperson =easyRandom.nextObject(Person.class);

In the previous example, Easy Random will:

  • Set all fields of typeString tofoo (using theRandomizer defined as a lambda expression)
  • Exclude the field namedage of typeInteger in classPerson.

The static methodsnamed,ofType andinClass are defined inorg.jeasy.random.FieldPredicateswhich provides common predicates you can use in combination to define exactly which fields to exclude.A similar class calledTypePredicates can be used to define which types to exclude from the object graph.You can of course use your ownjava.util.function.Predicate in combination with those predefined predicates.

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 thePerson type is defined as follows:

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

Streetstreet =newStreet(12, (byte)1,"Oxford street");Addressaddress =newAddress(street,"123456","London","United Kingdom");Personperson =newPerson("Foo","Bar","foo.bar@gmail.com",Gender.MALE,address);

And if these classes do not provide constructors with parameters (may be some legacy types you can't change), you would write:

Streetstreet =newStreet();street.setNumber(12);street.setType((byte)1);street.setName("Oxford street");Addressaddress =newAddress();address.setStreet(street);address.setZipCode("123456");address.setCity("London");address.setCountry("United Kingdom");Personperson =newPerson();person.setFirstName("Foo");person.setLastName("Bar");person.setEmail("foo.bar@gmail.com");person.setGender(Gender.MALE);person.setAddress(address);

With Easy Random, generating a randomPerson object is done withnew EasyRandom().nextObject(Person.class).The library willrecursively 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.TestpublicvoidtestSortAlgorithm() {// Givenint[]ints =easyRandom.nextObject(int[].class);// Whenint[]sortedInts =myAwesomeSortAlgo.sort(ints);// ThenassertThat(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.TestpublicvoidtestPersistPerson()throwsException {// GivenPersonperson =easyRandom.nextObject(Person.class);// WhenpersonDao.persist(person);// ThenassertThat("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 thewiki.

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 inmaintenance 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 theissue tracker.

Core team and contributors

Core team

Awesome contributors

Thank you all for your contributions!

License

TheMIT License. SeeLICENSE.txt.

About

The simple, stupid random Java beans/records generator

Topics

Resources

License

MIT, MIT licenses found

Licenses found

MIT
LICENSE.txt
MIT
licence-header-template.txt

Stars

Watchers

Forks

Contributors38

Languages


[8]ページ先頭

©2009-2026 Movatter.jp