Quick Way to Generate Mock Data In Java

  • Post last modified:December 15, 2022
  • Reading time:3 mins read
Photo by Angely Acevedo on Unsplash

Introduction

  • In this article we will generate mock data using Java Streams API
  • Idea is that to use Stream generator() method and then use it to generate custom data types such as emailID.

Generate Infinite Sequence of UUID

  • Streams API provides generate method that takes supplier object. Supplier is a functional interface that takes no input but return an output.
  • So we can build any logic as functional argument and pass to generate method.
  • In below example, we are generating UUID instance as infinite sequence.
private static void streamGenerate(){
     Supplier<UUID> supplier = () -> UUID.randomUUID();
     Stream<UUID> generate = Stream.generate(supplier);
     generate.forEach(a-> System.out.println(a));
}
@imsurajmishra

Generate Infinite Sequence of Messages

  • We can use above logic to implement custom logic to generate any object.
    Let’s consider a case where we are building a PubSub message publisher client and we want to mimic generating infinite sequence of messages that client need to publish.
  • We can easily extend the stream generator logic to build that . Below is our Message POJO that takes message ID and message itself.
 private static void streamMessage(){
        AtomicInteger atomicInteger = new AtomicInteger();
        Supplier<Message> supplier = () -> {
            Message message = new Message(new Random().nextInt(), "Message : "+atomicInteger.getAndIncrement());
            return message;
        };

        Stream.generate(supplier)
                .forEach(a-> System.out.println("Message Published: " +a.toString()));
    }
  • Below we have defined our supplier that returns Message object.
    We again used Stream generator that generates the infinite sequence of Message object and Print it.
   static class Message{
       int id;
       String message;

       public Message(int id, String message) {
           this.id = id;
           this.message = message;
       }

       @Override
       public String toString() {
           return "Message{" +
                   "id=" + id +
                   ", message='" + message + '\'' +
                   '}';
       }
   }

Generating Mock emailID data

  • In below example we will use stream generator to generate mock emailID data.
  • We have created list of email domains that we would like to see in our emailId.
  • The we build Supplier instance that first generate random userName and then concatenate with random domain that is picked from our domain list.
  • Once we have supplier instance ready we can call this method and provide size as number of emailId that we need.
    private static String generateUserName() {
       String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
       Random random = new Random();
       StringBuilder userName = new StringBuilder();
       for(int i=0;i<10;i++){
           userName.append(chars.charAt(random.nextInt(chars.length())));
       }
       return userName.toString();
    }
  • Below is the code to generate random username. Logic is to just pick random characters and append for the defined number of length for userName.
    private static void streamMailId(long size) {
       List<String> domain = List.of("@gmail.com", "@Yahoo.com", "@outlook.com");

       Supplier<String> supplier = () ->{
           String userName = generateUserName();
           Random random = new Random();
           int index = random.nextInt(domain.size());
           return userName+domain.get(index);
       };

       Stream.generate(supplier).limit(size).forEach(a-> System.out.println(a));
    }
  • Once we execute our client code we will see below output.
  • So it’s very easy to generate mock data with the help of generate feature and adding custom supplier logic.

Conclusion

  • In this article we used Streams api generate() method to generate infinite sequence of data.
  • We looked into custom mock data implementation such as emailId and message type.

Bonus Tip

Leave a Reply