DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Velocity 101 Unit Tests

  • submit to reddit
        // Unit tests for the Velocity 101 code. Note that the second test is
// actually a test to confirm that the function returns a failure
// correctly when the Velocity template file is not found.
// Be sure to get the test.vm file that goes with these unit tests.

package com.johnmunsch.util;

import org.apache.velocity.VelocityContext;

import junit.framework.TestCase;

public class BoilerplateTest extends TestCase {
    private VelocityContext context = null;
    private String testTemplate = null;

    protected void setUp() throws Exception {
        context = new VelocityContext();
        testTemplate = System.getProperty("testTemplate");

     * A very basic test to see if we can get a word inserted into a template
     * with the Boilerplate class.
     * @throws Exception 
    public void testApply() throws Exception {
        context.put("foo", "Velocity");
        String output = Boilerplate.apply(context, testTemplate);
        assertEquals(output, "<html><body>Hello Velocity World!</body><html>");
     * Same sort of test as above except this time we specify a bogus name for
     * the template file and we expect to get an exception. The failure occurs
     * only if we don't have an exception thrown.
    public void testApply2() {
        context.put("foo", "Velocity");

        try {
            Boilerplate.apply(context, "heyheypaula.vm");
        } catch (Exception e) {
            // We expect an exception. Failure is when we don't see one.

// This is a required file for the unit tests in "Velocity 101 Unit Tests". 
// Put it into a file and make sure that the filename is passed into the unit
// test above as a System property.

<html><body>Hello $foo World!</body><html>


Demetrios Kyriakis replied on Wed, 2007/02/21 - 8:48am

Thank you for the nice example. It would be however much better if it wouldn't use the System property. Also your snippet would look good in the official Velocity documentation.