JUnit4参数化和理论示例
我始終依靠TestNG將參數(shù)傳遞給測試方法,以便為我的測試或套件提供一些靈活性。
但是,使用JUnit4可以實現(xiàn)相同的靈活性。
要使用它很簡單:
JUnit將創(chuàng)建ParameterizedTest類的實例,并為靜態(tài)集合中定義的每一行運行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將根據(jù)提供的DataPoint和變量的類型使用所有可能的組合將方法市場稱為@Theory。 PRICE_BD DataPoint僅在最后一個方法中使用,唯一一個在其方法參數(shù)中接受BigDecimal的方法。
只有滿足Assume.assumeThat()條件的參數(shù)才能通過asser測試。 不滿足Assume.assumeThat()條件的組合將被靜默忽略。
參考:來自我們的JCG合作伙伴 Marco Castigliego的“ JUnit4參數(shù)化和理論” ,位于“ 刪除重復并修復不良名稱”博客中。
翻譯自: https://www.javacodegeeks.com/2012/11/junit4-parameterized-and-theories-examples.html
總結
以上是生活随笔為你收集整理的JUnit4参数化和理论示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 虚拟机安装xp系统遇到问题(虚拟机安装不
- 下一篇: 小米账号如何找回密码