注意:
在Eclipse中因为版本问题,可能无法使用@parameters(name = "xxx"),详见解决办法(文章的最后部分: IDE Bug - Eclipse):
https://github.com/junit-team/junit/wiki/Parameterized-tests
1. MathUtils – 参数化测试
查看一个简单的 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. 请参考以下的输出:
2. DomainUtils – 参数化测试
查看域名验证程序。
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 }, { "yiibai.com", true }, { "-yiibai.com", false }, { "yiibai-.com", false }, { "3423kjk", false }, { "mk#$kdo.com", false } } ); } @Test public void test_validDomains() { assertEquals(expected,DomainUtils.isValidDomainName(domain)); } }
输出结果:
完成