views:

149

answers:

1

I am using data-driven test suites running JUnit 3 based on Rainsberger's JUnit Recipes. The purpose of these tests is to check whether a certain function is properly implemented related to a set of input-output pairs.

Here is the definition of the test suite:

public static Test suite() throws Exception {
    TestSuite suite = new TestSuite();
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.set(2009, 8, 05, 13, 23); // 2009. 09. 05. 13:23
    java.sql.Date date = new java.sql.Date(calendar.getTime().getTime());
    suite.addTest(new DateFormatTestToString(date, JtDateFormat.FormatType.YYYY_MON_DD, "2009-SEP-05"));
    suite.addTest(new DateFormatTestToString(date, JtDateFormat.FormatType.DD_MON_YYYY, "05/SEP/2009"));
    return suite;
}   

and the definition of the testing class:

public class DateFormatTestToString extends TestCase {

    private java.sql.Date date;
    private JtDateFormat.FormatType dateFormat;
    private String expectedStringFormat;

    public DateFormatTestToString(java.sql.Date date, JtDateFormat.FormatType dateFormat, String expectedStringFormat) {
        super("testGetString");
        this.date = date;
        this.dateFormat = dateFormat;
        this.expectedStringFormat = expectedStringFormat;
    }

    public void testGetString() {
        String result = JtDateFormat.getString(date, dateFormat);
        assertTrue( expectedStringFormat.equalsIgnoreCase(result));
    }
}

How is it possible to test several input-output parameters of a method using JUnit 4?

This question and the answers explained to me the distinction between JUnit 3 and 4 in this regard. This question and the answers describe the way to create test suite for a set of class but not for a method with a set of different parameters.

Solution:

Based on drscroogemcduck's answer this is the exact page what helped.

+1  A: 

the really simple way:

you can always have a method:

checkGetString(date, dateFormat, expectedValue)

and then just have a method

@Test
testGetString:

  checkGetString(date1, '...', '...');
  checkGetString(date2, '...', '...');

the nicer way:

http://junit.sourceforge.net/javadoc_40/org/junit/runners/Parameterized.html

or better junit theories:

http://isagoksu.com/2009/development/agile-development/test-driven-development/using-junit-datapoints-and-theories/

drscroogemcduck
With the "really simple way" how would you ensure that tests are running independently and setup is performed between checkGetString calls?
rics
The example of Parameterized smells for me: duplicate definition of Fibonacci parameters?
rics
checkGetString has all of its state inside the method and none in the class so it is independent.
drscroogemcduck
In this case yes, but in general it is not necessary. For example I would like to test some database-related functions and I need a new connection for each test.
rics