LOADING

Type to search

Java REST Assured

JSON Object using Velocity Engine and Template

Share

We can generate JSON object using Velocity Engine, Velocity is a Java based templating engine from Apache.

Velocity permits you to use a simple yet powerful template language to reference objects defined in Java code.

Velocity is an open source web framework used to generate XML, SQL, PostScript and most other test based formats.

For use Velocity Engine you need to first import “org.apache.velocity” library to your project. If you are using maven framework you can add this library as a dependency (How to add dependency in maven).

First create an object reference for VelocityEngine()class.

VelocityEngine vEngine = new VelocityEngine();

Now let us set runtime velocity class loader to refer templates from resources directory.

vEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
vEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

It’s time to initiate runtime velocity engine.

vEngine.init();

After initializing velocity engine, read the required template from the velocity resource management system.

Create a “jsonSample.json” template in the “jsontemplates” folder under “Resources” folder of the project.

ResourcesFolder-VelocityFig.1

For instance,

{
  "name": {
    "firstname": "${firstName}",
    "lastname": "${lastName}"
  },
  "mobile": "${mobile}",
  "role":  ${role},
  "address": {
    "country": "${country}",
    "state": "${state}",
    "city": "${city}",
    "street": "${street}"
  },
  "email": "${email}"
}

Now read the template “jsonSample.json” and store it using a “Template” object.

Template t = vEngine.getTemplate("/jsontemplates/jsonSample.json");

After that assign values to each variable of the template, using “VelocityContext“.

VelocityContext ctx = new VelocityContext();
        ctx.put("firstName", "testing");
        ctx.put("lastName", "Mag");
        ctx.put("street", "");
        ctx.put("city", "");
        ctx.put("state", "");
        ctx.put("country", "");
        ctx.put("email","admin@testingmag.in");
        ctx.put("mobile", "");

In our example, everything is straight forward except for creating JSONArray "role": ["admin","contributor"],.

Therefore, we use “JSONArray” collection and “Arrays” class to achieve this.

ctx.put("role", new JSONArray(Arrays.asList("admin","contributor")));

Finally, we merge template and put the rendered stream into the writer using “StringWriter” class and “merge” method of “VelocityEngine”.

StringWriter wrt = new StringWriter();
t.merge(ctx, wrt);

Above all, let us look into the complete code as whole.

 String  res = "/jsontemplates/jsonSample.json";
        
VelocityEngine vEngine = new VelocityEngine();
//Set velocity class loader as to refer templates from resources directory.
vEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
vEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
         
//Initialize the Velocity runtime engine
vEngine.init();
         
Template t = vEngine.getTemplate(res);
VelocityContext ctx = new VelocityContext();
ctx.put("firstName", "testing");
ctx.put("lastName", "Mag");
ctx.put("street", "");
ctx.put("city", "");
ctx.put("state", "");
ctx.put("country", "");
ctx.put("role", new JSONArray(Arrays.asList("admin","contributor")));
ctx.put("email","admin@testingmag.in");
ctx.put("mobile", "");
         
// Merges a template and puts the rendered stream into the writer
StringWriter wrt = new StringWriter();
t.merge(ctx, wrt);
         
System.out.print(wrt.toString());

In conclusion, using velocity engine, we can achieve data driven testing of your API’s by having JSON templates based on the schema.

Leave a Comment

Your email address will not be published. Required fields are marked *