2010-05-12 50 views
1

我正在使用基於Rainsberger's JUnit Recipes的運行JUnit 3的數據驅動的測試套件。 這些測試的目的是檢查某個函數是否與一組輸入 - 輸出對相關地執行得當。如何在Junit 4中重寫JUnit 3的數據驅動測試套件?

下面是測試套件的定義:

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

怎麼可能使用測試的方法的幾個輸入輸出參數JUnit 4?

This question答案向我解釋了JUnit 3和4在這方面的區別。 This question和答案描述了爲一組類創建測試套件的方式,但是不能爲具有一組不同參數的方法創建測試套件。

解決方案

基於drscroogemcduck的答案,這是the exact page什麼幫助。

回答

1

的非常簡單的方法:

你總是可以有一個方法:

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/

+0

隨着「非常簡單的方法」你將如何保證測試獨立運行,並checkGetString電話之間進行設置? – rics 2010-05-12 11:19:49

+0

對我來說參數化的氣味的例子:斐波那契參數的重複定義? – rics 2010-05-12 11:26:47

+0

checkGetString在方法內部具有所有狀態,在類中沒有任何狀態,因此它是獨立的。 – benmmurphy 2010-05-12 11:32:55