From JUnit to SpringUnit Tests

Consolidating Data Retrieval

Previous Next
After Adding Syntactic Sugar it was plain that the code inside each test was redundant. For the first time, we refactor runValid and runInvalid, as shown here.
    protected void runValid() throws Exception {
        Integer day = (Integer)getObject("day");
        Integer month = (Integer)getObject("month");
        Integer year = (Integer)getObject("year");
        Integer expectedDay = (Integer)getObject("expectedDay");
        Integer expectedMonth = (Integer)getObject("expectedMonth");
        Integer expectedYear = (Integer)getObject("expectedYear");
        CompositeDate subject = new CompositeDate(year, month, day);
        assertTrue(expectedMonth == subject.getMonth());
        assertTrue(expectedDay == subject.getDay());
        assertTrue(expectedYear == subject.getYear());
    }

    protected void runInvalid() throws Exception {
        Integer day = (Integer)getObject("day");
        Integer month = (Integer)getObject("month");
        Integer year = (Integer)getObject("year");
        try {
            new CompositeDate(year, month, day);
            fail("Exception not thrown");
        }
        catch (InvalidDateException ex) {
        }
    }
The effect on the tests is dramatic.
    public void testJan01() throws Exception {
        runValid();
    }
	
    // More valid tests here

    public void testFeb29Leap2004() throws Exception {
        runValid();
    }

    public void testApr31() throws Exception {
        runInvalid();
    }
	
    // More invalid tests here

    public void testFeb29NoLeap() throws Exception {
        runInvalid();
    }
At this point, all of the test logic has been refactored into two methods. In Unifying the Test Algorithm we reduce this to one.
Previous Next