Home > Articles > Software Development & Management > Agile

  • Print
  • + Share This

Unit Tests

The first step in refactoring is to create unit tests that verify the basic functionality. If you're doing Extreme Programming (XP) with incremental, test-first programming, those tests exist already as a by-product of that process.

The following test requires a file named template.html that contains the text "xxx%CODE%yyy%ALTCODE%zzz".

import java.io.*;
import junit.framework.*;

public class CodeReplacerTest extends TestCase {
  CodeReplacer replacer;

  public CodeReplacerTest(String testName){super(testName);}

  protected void setUp() {replacer = new CodeReplacer();}

  public void testTemplateLoadedProperly() {
    try {
      replacer.substitute("ignored", 
                    new PrintWriter(new StringWriter()));
    } catch (Exception ex) {
      fail("No exception expected, but saw:" + ex);
    }

    assertEquals("xxx%CODE%yyy%ALTCODE%zzz\n",
                 replacer.sourceTemplate);
  }

  public void testSubstitution() {
    StringWriter stringOut = new StringWriter();
    PrintWriter testOut = new PrintWriter (stringOut);
    String trackingId = "01234567";
    
    try {
      replacer.substitute(trackingId, testOut);
    } catch (IOException ex) {
      fail ("testSubstitution exception - " + ex);
    }

    assertEquals("xxx01234567yyy01234-567zzz\n",
                 stringOut.toString());
  }
}

This code uses the JUnit unit-testing framework introduced in the previous chapter.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.