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

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Velocity 101 Unit Tests

// 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>

Email 101 Unit Tests

// Two unit tests for my Email 101 code. The first expects connection information to
// be in the System properties. That can be setup as part of running the unit tests
// from either Ant or Eclipse. Note: The first test only confirms that the send occurs
// without error, not that the email was actually received or received at the correct
// address.
//
// The second test trashes the SMTP server name and then confirms that it results in
// an exception being thrown from the mail sending code.

package com.johnmunsch.util;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import junit.framework.TestCase;

public class MailTest extends TestCase {
    String from = null;
    String to = null;
    String title = null;
    String textBody = null;
    String htmlBody = null;
    String smtpServer = null;
    
    /* (non-Javadoc)
     * @see junit.framework.TestCase#setUp()
     */
    protected void setUp() throws Exception {
        from = System.getProperty("from");
        to = System.getProperty("to");
        title = System.getProperty("title");
        textBody = System.getProperty("textBody");
        htmlBody = System.getProperty("htmlBody");
        smtpServer = System.getProperty("smtpServer");
    }

    /**
     * This is a terrible test. It could fail just as easily because it is 
     * incorrectly supplied with parameters as due to any failure in the code.
     * @throws MessagingException 
     * @throws AddressException 
     */
    public void testSendMail() throws AddressException, MessagingException {
        Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
    }
    
    /**
     * Same test as above except that we screw up the smtpServer address so it
     * is absolute garbage. In that case we should see a failure, which we are
     * looking for, and we throw an error if we _don't_ see some kind of
     * exception.
     */
    public void testSendMailWithBadServer() {
        smtpServer = "garbageingarbageout";
        
        try {
            Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
            
            fail();
        } catch (AddressException e) {
            // Exception good, no exception bad.
        } catch (MessagingException e) {
            // Exception good, no exception bad.
        }
    }
}

JUnit: Convenient use of TestSuite based on parameterized TestCases

Here's a frequently (at least for me) occurring problem: let's say
you have a TestCase where each testXXX() method really does mostly
the same thing, parameterized by some instance variables. For instance,
I have a file consisting of good data for each parameter, such as:

goodAAA=foo
goodBBB=bar
goodCCC=baz
...


You don't want to create tens or hundreds of methods (testAAA(),
testBBB(), etc.) by copying and pasting. So you create a TestCase that
has:

- An field called, say, key

- A single testKey() method that, based on the
key, gets the good data, gets the test data and compares them.

- static suite() method that, in a loop, creates instances of your
TestCase and sets their keys appropriately.

This is all well and good. But when you run it, a failure will always
show up in testKey() method in JUnit's UI. (Sure, you can add a message
that shows the key for which it failed, but it does not give
you an at-a-glance feedback.)

So for convenience, you override getName() to return key. Now
it's very easy to tell, by merely glancing at that JUnit bar, what
failed.

But if you run it within IDE, say, Eclipse, you want to click on the
failed test so that Failure Trace appears, where you can click on any
Stack Trace Element and get to the exact line of failure in your code.
But because the failed test's name is based on the key field, it does
not correspond to a real testXXX() method in your TestCase. So your
IDE can't take you to the code that failed.

Here's how to override getName() to get the best of both worlds:

public String getName() {
    StackTraceElement[] st = new Throwable().getStackTrace();
    if (st.length < 4 || !st[3].getMethodName().equals("endTest")) {
        return key; 	  // Meaningful name to appear in the bar
    } else {
        return "testKey"; // Real method name to appear in Failure Trace
    }
}

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS