我始終依靠TestNG將參數傳遞給測試方法,以便為我的測試或套件提供一些靈活性。
但是,使用JUnit4可以實現相同的靈活性。
要使用它很簡單:
package com.marco.test;import java.util.Arrays;import java.util.Collection;import junit.framework.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.Parameterized;import org.junit.runners.Parameterized.Parameters;@RunWith(Parameterized.class)public class ParameterizedTest {@Parameterspublic static Collection data() {return Arrays.asList(new Object[][] {/* Sport Nation year totWinners */{ “basket”, “usa”, 2002, 5, },{ “soccer”, “argentina”, 2003, 2 },{ “tennis”, “spain”, 2004, 10 },{ “chess”, “ireland”, 2005, 0 },{ “eatingbananas”, “italy”, 2006, 20 }});}private final String sport;private final String nation;private final int year;private final int totWinners;public ParameterizedTest(String sport, String nation, int year, int totWinners) {this.sport = sport;this.nation = nation;this.year = year;this.totWinners = totWinners;}@Testpublic void test() {Assert.assertTrue(isDataCorrect(sport, nation, year, totWinners));}private boolean isDataCorrect(String sport2, String nation2, int year2, int totWinners2) {return true;}}
JUnit將創建ParameterizedTest類的實例,并為靜態集合中定義的每一行運行testCombination()方法(或標記為@Test的任何方法)。
理論
我喜歡JUnit4的另一個有趣的功能。 您可以在JUnit 4中使用Theories使用相同的測試方法來測試輸入的組合:
package com.marco.test;import static org.hamcrest.CoreMatchers.is;import java.math.BigDecimal;import org.junit.Assert;import org.junit.Assume;import org.junit.experimental.theories.DataPoint;import org.junit.experimental.theories.Theories;import org.junit.experimental.theories.Theory;import org.junit.runner.RunWith;@RunWith(Theories.class)public class TheoryTest {@DataPointpublic static int MARKET_FIRST_GOALSCORERE_ID = 2007;@DataPointpublic static int MARKET_WDW_ID = 2008;@DataPointpublic static BigDecimal PRICE_BD = new BigDecimal(6664.0);@DataPointpublic static double PRICE_1 = 0.01;@DataPointpublic static double PRICE_2 = 100.0;@DataPointpublic static double PRICE_3 = 13999.99;@Theorypublic void lowTaxRateIsNineteenPercent(int market_id, double price) {Assume.assumeThat(market_id, is(2008));Assume.assumeThat(price, is(100.0));// run your testAssert.assertThat(price, is(100.0));}@Theorypublic void highTaxRateIsNineteenPercent(int market_id, double price) {Assume.assumeThat(market_id, is(2007));Assume.assumeThat(price, is(13999.99));Assert.assertThat(price, is(13999.99));}@Theorypublic void highTaxRateIsNineteenPercent(int market_id, BigDecimal price) {Assume.assumeThat(market_id, is(2007));Assert.assertThat(price, is(BigDecimal.valueOf(6664)));}}
這次您需要將測試類標記為@RunWith(Theories.class),并使用@DataPoint定義要測試的屬性。
JUnit將根據提供的DataPoint和變量的類型使用所有可能的組合將方法市場稱為@Theory。 PRICE_BD DataPoint僅在最后一個方法中使用,唯一一個在其方法參數中接受BigDecimal的方法。
只有滿足Assume.assumeThat()條件的參數才能通過asser測試。 不滿足Assume.assumeThat()條件的組合將被靜默忽略。
參考:來自我們的JCG合作伙伴 Marco Castigliego的“ JUnit4參數化和理論” ,位于“ 刪除重復并修復不良名稱”博客中。
翻譯自: https://www.javacodegeeks.com/2012/11/junit4-parameterized-and-theories-examples.html