A Bee and a Pig in hay

Generate your test data from a template

Freemarker is a template engine in java to generate text output based on templates and data classes. You should write the templates in a custom language. The Language is the Freemarker Template Language (FTL).

With this template engine, you can generate your test data from a template. Lets have an example: I created A Persons class in a previous post. I simplify this example in this post.

public class Person {
    private String name;
   
    public Person(String name){
        this.name = name;
    }
}

I want to send the following data to a back-end in an xml structure. It can be some other structure too of course.

<person>
  <name></name>
</person>

I could write a wrapper to fill in the test in java. It is not that difficult. There is an easy way to implement the same with a template engine.

First I create the template. Afterwards Freemarker will fill in the template with the correct values.

<person>
  <name>${Person.name}</name>
</person>

In the template, you fill in the variables in ${} structures. Freemarker fills in the variables for you. You first have to create a data model in java.

The data model in java to fill in the template is a class that holds the data with getter and setter functions. I can make use of the builder pattern if the class gets to big.

public class Person {
    private String name;
 
    public Person(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }
}

The Freemarker library needs one more thing to create the output files. That is the glue code. That code glues the template and the data model together.

// Create the root hash. 
Map<String, Object> root = new HashMap<>(); 
 
Person person = new Person(); 
person.setName("Anne Bonny"); 

// and put it into the root 
root.put("Person", person); 

Template temp = cfg.getTemplate("person.template.file.txt");

Writer out = new OutputStreamWriter(System.out);

temp.process(root,out);

The output is now the following xml string:

<person>
  <name>Anne Bonny</name>
</person>

I explained in this post that you can generate your test data from a template with Freemarker. The java code is not complicated and the engine is easy to use. It is a nice library to use.

About the author

I currently work as a Test Automation Consultant at b.ignited. Here I work for different clients in different industries to help them start and speed up their testing cycles

I’ve been testing software since 2000 when I became involved in testing telephone applications and hardware. Since then, I’ve been able to expand my experience by testing a variety of embedded, web, mobile and desktop applications. I have used various development methodologies from waterfall to agile.

I consider myself to be a lifelong learner.