Never been to DZone Snippets before?

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

Velocity 101 Unit Tests (See related posts)

// 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");
            
            fail();
        } 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>

Comments on this post

dkyriakis posts on Feb 21, 2007 at 10:11
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.

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts