Re: [問題] 撰寫 junit Test Suite 的正確方法

看板java作者 ( )時間12年前 (2011/12/19 11:41), 編輯推噓7(700)
留言7則, 7人參與, 最新討論串2/2 (看更多)
我在想你可能把不少東西混在一起了 1. JUnit3和JUnit4的差別。 JUnit3 和 JUnit4 是很大的一個分水嶺。 過去JUnit3使用的方式,是靠繼承和特定的naming convention,利用reflection讓JUnit Runner能夠分辨Test。但在Java 1.5 release後,JUnit4則是完全拋棄先前的方法,採用 宣告Annotaion的方式讓Runner來分辨。也因此在JUnit4寫一般的test時是用不到繼承的 同時,在package name也作了修改 JUnit3是 junit.framework.* JUnit4是 org.junit.* 而JUnit4為了相容性,jar檔裡仍然保有JUnit3的package和classes。 因此你的狀況比較像是在同一個TestCase裡把3和4的寫法混用,然後還用3的Runner去跑4 的Test。基本上建議還是以4為主較好,而且JUnit3的TestCase/TestSuite其實都能在 4跑,且況把3的code migrate到4其實也不會很麻煩。 2. Parameterized test 你文章中給的"Test suite"其實不叫Test suite,是叫Paramaterized Test code裡混用了JUnit3和JUnit4的寫法 以下是JUnit4的寫法 @RunWith(Parameterized.class) public class MyParameterizedTest { // No need to extend anything @Parameters public static Collections<Object[]> parameters() { Object[][] parameters = new Object[][]{ {"parameter1"}, {"parameter2"} }; return Arrays.asList(parameters); } private String parameter; public MyParameterizedTest(String parameter) { this.parameter = parameter; } @Test public void test() { System.out.println("parameter : " + parameter); } } 3. Test Suite JUnit4裡,TestSuite也一樣是用Annotaion來標示 而且整個class也就只有Annotaion @RunWith(Suite.class) // Treat me as a test suite! @SuiteClasses(MyParameterizedTest.class, MyAnotherTest.class)// Run these tests public class MyTestSuite { } TestSuite裡也可以跑TestSuite,一樣放入SuiteClasses即可 @RunWith(Suite.class) @SuiteClasses(MyTestSuite.class) public class AllTests { } ==================================================== 你的問題應該都在於把3和4的code混在一起使用了,希望這些簡單介紹能夠幫你釐清。 -- We who cut mere stones must always be envisioning cathedrals. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.27.133.188

12/20 00:01, , 1F
推! 多虧有這篇, 我解了很多長久以來的問題, 真是感激!!
12/20 00:01, 1F

12/20 10:43, , 2F
難得看到這種長文,我都要落淚了 T_T
12/20 10:43, 2F

12/21 11:21, , 3F
好文~~~~真是太感動了~
12/21 11:21, 3F

12/22 02:05, , 4F
路過幫推。
12/22 02:05, 4F

12/23 20:30, , 5F
12/23 20:30, 5F

12/25 22:38, , 6F
12/25 22:38, 6F

02/10 12:22, , 7F
值得推薦
02/10 12:22, 7F
文章代碼(AID): #1Exh9HS6 (java)
文章代碼(AID): #1Exh9HS6 (java)