简体   繁体   中英

Recursively generating random objects in Java

What library / method can I use for deep generation of random objects for a given class in Java / Scala? By deep generation I mean recursively filling the entire object graph with random values, for both primitive and complex types.

The goal is to use randomly generated mock objects for tests.

To make the tests consistent and reproducible, the set of generated objects should be identical on every run.

As far as I know there are there are two powerful methods to randomly generate very large, arbitrary types of object. The first is called the recursive method (introduced by Wilf and Nijenhuis, formalized by Flajolet, van Cutsem and Zimmerman), the second is called Boltzmann sampling by Duchon, Flajolet, Louchard and Schaeffer.

In both methods, you give a structure definition (a "grammar") and you are returned with a large random object which is in accordance with the grammar.

Both have been used very successfully in wide scale testing of programs (similar to Haskell's QuickCheck ). Unfortunately, while there are some various implementations of the methods, I don't think there is a ready to use library for Java. For example of what can be done, you might want to check Yann Ponty's page with Java implementations of these methods for bioinformatics. If you were using OCaml, then Alexis Darrasse and Benjamin Canou have implemented a useful subset of Boltzmann sampling as a completely autonomous library for algebraic types (sumtypes).

The InPUT library can help you doing this in Java. You specify the structures in XML in a so called design space which defines the valid ranges. In the code then you simply call

IDesignSpace ds = new DesignSpace("designSpace.xml");
TheType o = ds.next("TheTypeId");

The object o is now randomly instantiated according to what you accept as valid value ranges in the XML. Here you find tutorials and examples. Reproducibility is addressed in this tutorial .

Some research showed me that there is a great framework for Scala called ScalaCheck , which was inspired by QuickCheck, which Jérémie mentioned above. Though it's build for Scala, it can be used in Java as well (though without the syntactic sugar)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM