清單 13 理論機制舉例
import static org.hamcrest.Matchers.*; //指定接下來要使用的Matcher匹配符 import static org.junit.Assume.*; //指定需要使用假設assume*來輔助理論Theory import static org.junit.Assert.*; //指定需要使用斷言assert*來判斷測試是否通過 import org.junit.experimental.theories.DataPoint; //需要使用注釋@DataPoint來指定數據集 import org.junit.experimental.theories.Theories; //接下來@RunWith要指定Theories.class import org.junit.experimental.theories.Theory; //注釋@Theory指定理論的測試函數 import org.junit.runner.RunWith; //需要使用@RunWith指定接下來運行測試的類 import org.junit.Test; //注意:必須得使用@RunWith指定Theories.class @RunWith(Theories.class) public class TheoryTest { //利用注釋@DataPoint來指定一組數據集,這些數據集中的數據用來證明或反駁接下來定義的Theory理論, //testNames1和testNames2這兩個理論Theory測試函數的參數都是String,所以Junit4.4會將這5個 //@DataPoint定義的String進行兩兩組合,統統一一傳入到testNames1和testNames2中,所以參數名year //和name是不起任何作用的,"2007"同樣有機會會傳給參數name,"Works"也同樣有機會傳給參數year @DataPoint public static String YEAR_2007 = "2007"; @DataPoint public static String YEAR_2008 = "2008"; @DataPoint public static String NAME1 = "developer"; @DataPoint public static String NAME2 = "Works"; @DataPoint public static String NAME3 = "developerWorks"; //注意:使用@Theory來指定測試函數,而不是@Test @Theory public void testNames1( String year, String name ) { assumeThat( year, is("2007") ); //year必須是"2007",否則跳過該測試函數 System.out.println( year + "-" + name ); assertThat( year, is("2007") ); //這里的斷言語句沒有實際意義,這里舉此例只是為了不中斷測試 } //注意:使用@Theory來指定測試函數,而不是@Test @Theory public void testNames2( String year, String name ) { assumeThat(year, is("2007")); //year必須是"2007",否則跳過該測試函數 //name必須既不是"2007"也不是"2008",否則跳過該測試函數 assumeThat(name, allOf( not(is("2007")), not(is("2008")))); System.out.println( year + "-" + name ); assertThat( year, is("2007") ); //這里的斷言語句沒有實際意義,這里舉此例只是為了不中斷測試 } 結果輸出: 第一個Theory打印出: 2007-2007 2007-2008 2007-developer 2007-Works 2007-developerWorks 第二個Theory打印出: 2007-developer 2007-Works 2007-developerWorks |
結束語