代码之家  ›  专栏  ›  技术社区  ›  rics

如何在junit4中重写junit3的数据驱动测试套件?

  •  1
  • rics  · 技术社区  · 16 年前

    Rainsberger's JUnit Recipes . 这些测试的目的是检查与一组输入-输出对相关的特定功能是否正确实现。

    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;
    }   
    

    以及测试类的定义:

    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));
        }
    }
    

    This question 答案向我解释了junit3和junit4在这方面的区别。 This question 答案描述了为一组类创建测试套件的方法,而不是为一组不同参数的方法。

    解决方案

    根据McDuck博士的回答这是 the exact page

    1 回复  |  直到 9 年前
        1
  •  1
  •   benmmurphy    16 年前

    最简单的方法是:

    你总是可以有一个方法:

    checkGetString(date, dateFormat, expectedValue)
    

    @Test
    testGetString:
    
      checkGetString(date1, '...', '...');
      checkGetString(date2, '...', '...');
    

    更好的方法是:

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

    或者更好的junit理论:

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