Question

I have two custom Date classes (let's call them DateV1 and DateV2), one being the super and the other the sub, both implementing exactly the same methods.
Starting from JUnit 4.x, parameterized tests seem to offer a way to test both classes within a single test class (although some people seem to find parameterized tests confusing and generally steer clear of them).

Because I'm new to JUnit (and, indeed, Java) and have been writing nothing but the simplest of tests, I'd like to hear from more proficient JUnit users how to tackle situations like these. I've been going over the theory in JUnit In Action, 2nd Ed., Manning, July 2010 but I'm having difficulties seeing how this would be used in a super/sub scenario.

It won't come as a surprise that I'm not including code because frankly I don't have any at the moment. I'm not asking for microwave code, but some pointers would be appreciated so I can be on my merry way and not write a bunch of boilerplate.

Was it helpful?

Solution

Assuming you have such DateV1 and DateV2:

public class DateV1 {

    protected final Date date;

    public DateV1(Date date) { 
        this.date = date;
    }

    public int getYear() {
        return 1900 + date.getYear();
    }
}

public class DateV2 extends DateV1 {

    private Calendar cal;

    public DateV2(Date date) {
        super(date);
        cal = Calendar.getInstance();
        cal.setTime(date);      
    }

    public int getYear() {
        return cal.get(Calendar.YEAR);
    }
}

The test might look like:

@RunWith(value = Parameterized.class)
public class DateTest {

    private DateV1 date;

    public DateTest(DateV1 date) {
        this.date = date;
    }

    @Parameters
    public static Collection<Object[]> data() {
        final Date currDate = new Date();
        Object[][] data = new Object[][] { { new DateV1(currDate) }, { new DateV2(currDate) } };
        return Arrays.asList(data);
    }

    @Test
    public void getYearShouldReturn2013() {
        Assert.assertEquals(2013, date.getYear());
    }
}

However, there is one important question: Should your super and sub classes (DateV1 and DateV2) be tested in exactly the same way? Does the DateV2 class deliver exactly the same functionality as its superclass DateV1? If there is absolutely no difference in behavior between these classes why have the two? If there is a difference between the two then it should be addressed by your test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top