Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random data generator

Tags:

java

I have to fill every property of a given object with a random value. These are my requirements for it:

  • All properties are native Java type (int, double, String, etc)
  • I can use reflection
  • I can use Spring DirectFieldAccessor

I don't want to re-invent the square wheel so I prefer to ask. For now I came up with this:

Get all properties name with:

Field field : myObject.getClass().getDeclaredFields()

Iterate over those fields and get their class.

Use a giant switch statement for each known native Java type and generate a random value.

What do you think?

like image 981
sliders_alpha Avatar asked Aug 24 '26 20:08

sliders_alpha


1 Answers

Another option is QuickTheories. It looks like:

import static org.quicktheories.QuickTheory.qt;
import static org.quicktheories.generators.SourceDSL.*;

public class SomeTests {

  @Test
  public void addingTwoPositiveIntegersAlwaysGivesAPositiveInteger(){
    qt()
      .forAll(integers().allPositive()
          , integers().allPositive())
      .check((i,j) -> i + j > 0); 
  }

  @Test
  public void someTheoryOrOther(){
    qt()
      .forAll(integers().allPositive()
          , strings().basicLatinAlphabet().ofLengthBetween(0, 10)
          , lists().allListsOf(integers().all()).ofSize(42))
      .assuming((i,s,l) -> s.contains(i.toString())) // <-- an assumption
      .check((i,s,l) -> l.contains(i) && s.contains(i.toString()));
  }
}
like image 91
Andbdrew Avatar answered Aug 26 '26 10:08

Andbdrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!