注意:
在Eclipse中因為版本問題,可能無法使用@parameters(name = "xxx"),詳見解決辦法(文章的最後部分: IDE Bug - Eclipse):
https://github.com/junit-team/junit/wiki/Parameterized-tests
檢視一個簡單的 add 方法。
MathUtils.java
package com.yiibai.match.utils; public class MathUtils { public static int add(int a, int b) { return a + b; } }
這裡有一個為上面的JUnit測試類,閱讀不言自明的註釋。
MathUtilsTest.java
package com.yiibai.match.utils; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class MathUtilsTest { private int numberA; private int numberB; private int expected; //parameters pass via this constructor public MathUtilsTest(int numberA, int numberB, int expected) { this.numberA = numberA; this.numberB = numberB; this.expected = expected; } //Declares parameters here @Parameters(name = "{index}: add({0}+{1})={2}") public static Iterable<Object[]> data1() { return Arrays.asList(new Object[][] { { 1, 1, 2 }, { 2, 2, 4 }, { 8, 2, 10 }, { 4, 5, 9 } }); } @Test public void test_add() { assertEquals(expected,MathUtils.add(numberA, numberB)); } }
什麼是 {0}, {1} 和 {2}?
如果引數是 「{ 3, 4, 7 }」, 那麼 {0} = 3, {1} = 4, {2} = 7. 請參考以下的輸出:
檢視域名驗證程式。
DomainUtils.java
package com.yiibai.regex.utils; import java.util.regex.Pattern; public class DomainUtils { private static Pattern pDomainName; private static final String DOMAIN_NAME_PATTERN = "^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$"; static { pDomainName = Pattern.compile(DOMAIN_NAME_PATTERN); } //is this a valid domain name? public static boolean isValidDomainName(String domainName) { return pDomainName.matcher(domainName).find(); } }
這裡有一個 JUnit 測試上面的類。
DomainUtilsTest.java
package com.yiibai.regex.utils; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public class DomainUtilsTest { private String domain; private boolean expected; public DomainUtilsTest(String domain, boolean expected) { this.domain = domain; this.expected = expected; } @Parameters(name= "{index}: isValid({0})={1}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { { "google.com", true }, { "tw511.com", true }, { "-tw511.com", false }, { "yiibai-.com", false }, { "3423kjk", false }, { "mk#$kdo.com", false } } ); } @Test public void test_validDomains() { assertEquals(expected,DomainUtils.isValidDomainName(domain)); } }
輸出結果:
完成