有时,您会遇到一个问题,就是尖叫使用“参数化”测试,而不是多次复制/粘贴相同的方法。 测试方法基本上是相同的,唯一改变的是传入的数据。在这种情况下,请考虑创建一个利用JUnit中的“ Parameterized ”类的测试用例。
我最近遇到了一个问题,其中我们对电子邮件地址的验证不允许使用unicode字符。 解决方法非常简单,更改正则表达式以允许这些字符。 接下来,该测试更改了。 我决定不对每组数据复制/粘贴单独的方法,而是决定学习Parameterized方法。 结果如下。 数据包括预期结果和要验证的电子邮件地址。
JUnit测试类
package com.mycompany.client;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.mycompany.test.TestServiceUtil;
/**
* Parameterized test case for validating email addresses against a regular expression.
* We need to allow unicode characters in the userid portion of the email address, so
* these test cases where created to help validate the validateEmailAddress method
* in the FieldValidationController class.
*
* @author mmiller
*
*/
@RunWith(Parameterized.class)
public class TestFieldValiationController {
@Parameters(name = "{index}: {1} is valid email address = {0}")
public static Iterable<Object> data() {
return Arrays.asList(new Object[][] {
{ true, "john@mycomp.com" }, { true, "john123@mycomp.com" },
{ true, "j+._%20_-brown@mycomp.com" }, { true, "123@mycomp.com" },
{ false, "john brown@mycomp.com" }, { false, "123@mycomp" },
{ false, "john^brown@mycomp.com" }, { true , "1john@mycomp.com" },
{ false, "john#brown@mycomp.com" }, { false, "john!brown@mycomp.com" },
{ false, "john()brown@mycomp.com" }, { false, "john=brown@mycomp.com" },
{ true, "johñ.brown@mycomp.com" }, { false, "john.brown@mycomp.coñ" },
{ true, "johú@mycomp.com" }, { true, "johíáó@mycomp.com" }
});
}
private boolean expected;
private String emailAddress;
public TestFieldValiationController(boolean expected, String emailAddress) {
this.expected = expected;
this.emailAddress = emailAddress;
TestServiceUtil.getInstance();
}
@Test
public void validateEmail() {
assertEquals(expected, FieldValidationController.getInstance().validateEmailAddress(emailAddress));
}
}
希望这可以帮助!
翻译自: https://www.javacodegeeks.com/2014/03/parameterized-junit-tests.html