Random Beans


Source link: https://github.com/benas/random-beans


Random Beans
Because life is too short to generate random Java™ beans by hand..


Latest news

  • 19/06/2017: Version 3.7.0 is released. Checkout what's new in the change log.
  • 05/03/2017: Version 3.6.0 is out with new features and bug fixes. See all details in the change log.

What is Random Beans ?

Random Beans is a library that generates random Java beans. Let's say you have a class Person and you want to generate a random instance of it, here we go:

Person person = random(Person.class);

The static method EnhancedRandom.random is able to generate random instances of a given type.

Let's see another example. If you want to generate a random stream of 10 persons, you can use the following snippet:

Stream<Person> persons = randomStreamOf(10, Person.class);

This second static method of the EnhancedRandom API generates a stream of random instances of a given type.

What is this EnhancedRandom 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? Random Beans provides the EnhancedRandom API that extends (enhances) java.util.Random with a method called nextObject(Class type). This method is able to generate a random instance of any arbitrary Java bean:

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

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

EnhancedRandom random = EnhancedRandomBuilder.aNewEnhancedRandomBuilder()
 .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)
 .build();

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

In most cases, default options are enough and you can use a static import of the EnhancedRandom.random(Class object) as seen previously.

Random beans allows you to control how to generate random data through the Randomizer interface and makes it easy to exclude some fields from the object graph using the fluent FieldDefinition API:

EnhancedRandom enhancedRandom = EnhancedRandomBuilder.aNewEnhancedRandomBuilder()
 .randomize(String.class, (Randomizer<String>) () -> "foo")
 .exclude(field().named("age").ofType(Integer.class).inClass(Person.class).get())
 .build();
  Person person = enhancedRandom.nextObject(Person.class);

Why Random Beans ?

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 Random Beans, 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 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("[email protected]");
 person.setGender(Gender.MALE);
 person.setAddress(address);

With Random Beans, generating a random Person object is done with random(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 = aNewEnhancedRandom().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 = random(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 random beans can be useful, you can find a non exhaustive list in the wiki.

Contribution

You are welcome to contribute to the project with pull requests on GitHub.

If you believe you found a bug, please use the issue tracker.

If you have any question, suggestion, or feedback, do not hesitate to use the Gitter channel of the project.

Core team and contributors

Core team

Awesome contributors

Thank you all for your contributions!

Resources

Shows a graphic representation of the sounds captured by the microphone on Android

This a is a ready-to-use library that encapsulate the Android Download Manager. Using an interface you can easily connect to your Activity or Fragment and used it. It runs on other process as an independent service.

Extension of RecyclerView that can get its scrolling synchronized with others of its kind.

An architecture for Android as a replacement of MVC.

A lightweight wrapper around realm-java which introduces reactive stream semantics to SQL operations.

Dexter is an Android library that simplifies the process of requesting permissions at runtime.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes