How to randomize an object: Map<Author, List<Book>> with EasyRandom in Java?

78 Views Asked by At

I'm trying to randomize an object: Map<Author, List> with easyRandom for testing.

For the moment I haven't get my code to compile. So my code is something like:

MapRandomizer<Author, List<Book>> mapRandomizer = new MapRandomizer<>(Author.class, ArrayList<Book>.class);
        Map<Author, List<Book>> map = mapRandomizer.getRandomValue(); 

But I don't know how to put the list (ArrayList.class???) as a parameter of the mapRandomizer.

Does anyone knows how to get my code to compile and create a random object of type: Map<Author, List>?

Thank you,

2

There are 2 best solutions below

2
Paymer On

Right now I'm trying to do it the long way:


    Author author1 = generator.nextObject(Author.class);
    Author author2 = generator.nextObject(Author.class);
    Author author3 = generator.nextObject(Author.class);
    
    List< Book> bookList1= generator.objects(Book.class, 3).collect(Collectors.toList());
    List< Book> bookList2= generator.objects(Book.class, 2).collect(Collectors.toList());
    List< Book> bookList3= generator.objects(Book.class, 4).collect(Collectors.toList());
    
    Map< Author, List< Book>> map= new HashMap<>();
    map.put(author1 , bookList1);
    map.put(author2 , bookList2);
    map.put(author3 , bookList3);

0
daniu On

You can't really create a random map without creating random entries. You'll need to be able to create each contained type (in your example Author and Book) randomly. Putting them in a list and map is just creating the proper containers then.

So what you really probably have is

class MapRandomizer<K, List<E>> {
 private ItemRandomizer<K> keyRandomizer;
 private ListRandomizer<E> listRandomizer;

 public Map<K, List<E>> createMap() {
  // random count, for each entry create random K and random List<E>
  // using keyRandomizer and listRandomizer
 }
}

with

class ListRandomizer<E> {
 private ItemRandomizer<E> entryRandomizer;

 public List<E> createList() {
  // random count, fill list with that amount of entries 
  // using the entry randomizer
 }
}

and then you can create your concrete randomizer with

MapRandomizer<Author, List<Book>> randomizer = new MapRandomizer<>(
 new AuthorRandomizer(), new ListRandomizer<Book>(new BookRandomizer())
);

In this, AuthorRandomizer and BookRandomizer will need to implement ItemRandomizer<Author> and ItemRAndomizer<Book>, respectively.

EDIT: since you posted your code in the reply, you should be easily able to wrap generate(Autor.class) to implement ItemRandomizer<Author>.