3

I'd like to generate unique, repeatable, simple values by Class. This is part of something I'm writing to validate Java beans, i.e. the firePropertyChange() is implemented correctly.

I've started implementing something along the lines of

class TestValueGenerator {
   private int counter;
   public Object getNextValue(Class<?> type) {
      counter++;
      if (type == byte.class) {
          return (byte)counter;
      } else if (type == short.class) {
          return (short)counter;
      } ... 
      // int, long, float, double, String, Date etc... 
   }
}

I'm building on top of openpojo, this does have existing generation functions, however they are implemented using random number generation seeded on current time, which I personally think is unwise for unit testing... e.g.

value = com.openpojo.random.RandomFactory.getRandomValue(fieldEntry);

Question

  • Is there any built-in Java method or external library to do this - am I reinventing the wheel?
Adam
  • 35,919
  • 9
  • 100
  • 137
  • 1
    Generally good idea, and I was thinking about same things. But actually I think, this will not be pure unit test since it relies on random values. BTW, look at http://stackoverflow.com/questions/32458/random-data-in-unit-tests – Andremoniy Feb 01 '16 at 11:59
  • Java donthave inbuilt counter generator but it has random number generator – Rais Alam Feb 01 '16 at 12:00
  • @Andremoniy Assuming calls to getNextValue() are in a deterministic order, which can be ensured by instantiating fresh TestValueGenerator in (at)Before method then test will not be random at all, and I believe will still qualify for pure unit test status :) – Adam Feb 01 '16 at 13:21

3 Answers3

2

What you are looking for is called property based testing. It is not build-in in JDK, but there are frameworks which already do this:

Possibly others.

Robert Bräutigam
  • 7,514
  • 1
  • 20
  • 38
1

While OpenPojo does use a date seed to stay random over time, it doesn't prevent you from over-riding its registered generators. For example to provide your own byte/Byte generator, just create a class that implements RandomGenerator, and register it in the framework as such:

RandomGeneratorService service = ServiceRegistrar.getRandomGeneratorService()
service.registerRandomGenerator(new MyByteRandomGenerator());

For example see ObjectRandomGenerator

Osman Shoukry
  • 294
  • 2
  • 6
0

Use PODAM,

PODAM is a lightweight tool to auto-fill Java POJOs with data. This comes handy when developing unit tests. Thanks to PODAM users now have a one-liner that does all the work them. ex:

PodamFactory factory = new PodamFactoryImpl();
List<AuthorDoc> authorDocs = factory.manufacturePojo(ArrayList.class, AuthorDoc.class);

For more details Podam tutorials

MadukaJ
  • 722
  • 6
  • 22