From JUnit to SpringUnit Tests

Eliminating the Test Name

Previous Next
In Separating Data from Algorithm, we can spot redundancy inside each test, because the name of the test is the index under which data values are stored. This value is actually provided by the JUnit framework at runtime, simply by calling the method, getName(). The next refactoring capitalizes on this fact.
package org.springunit.examples.constructor.junit.v4;

public class CompositeDateConstructorTest extends TestCase {
	
    public void testJan01() throws Exception {
        Integer day = (Integer)this.data.get(getName()).get("day");
        Integer month = (Integer)this.data.get(getName()).get("month");
        Integer year = (Integer)this.data.get(getName()).get("year");
        Integer expectedDay = (Integer)this.data.get(getName()).get("expectedDay");
        Integer expectedMonth = (Integer)this.data.get(getName()).get("expectedMonth");
        Integer expectedYear = (Integer)this.data.get(getName()).get("expectedYear");
        runValid(year, month, day, expectedYear, expectedMonth, expectedDay);
    }

    // More valid tests here

    public void testFeb29Leap2004() throws Exception {
        Integer day = (Integer)this.data.get(getName()).get("day");
        Integer month = (Integer)this.data.get(getName()).get("month");
        Integer year = (Integer)this.data.get(getName()).get("year");
        Integer expectedDay = (Integer)this.data.get(getName()).get("expectedDay");
        Integer expectedMonth = (Integer)this.data.get(getName()).get("expectedMonth");
        Integer expectedYear = (Integer)this.data.get(getName()).get("expectedYear");
        runValid(year, month, day, expectedYear, expectedMonth, expectedDay);
    }

    public void testApr31() throws Exception {
        Integer day = (Integer)this.data.get(getName()).get("day");
        Integer month = (Integer)this.data.get(getName()).get("month");
        Integer year = (Integer)this.data.get(getName()).get("year");
        runInvalid(year, month, day);
    }

    // More invalid tests here

    public void testFeb29NoLeap() throws Exception {
        Integer day = (Integer)this.data.get(getName()).get("day");
        Integer month = (Integer)this.data.get(getName()).get("month");
        Integer year = (Integer)this.data.get(getName()).get("year");
        runInvalid(year, month, day);
    }

}
Adding Syntactic Sugar removes even more clutter.
Previous Next