本文整理了Java中org.junit.runners.Parameterized
类的一些代码示例,展示了Parameterized
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Parameterized
类的具体详情如下:
包路径:org.junit.runners.Parameterized
类名称:Parameterized
[英]The custom runner Parameterized
implements parameterized tests. When running a parameterized test class, instances are created for the cross-product of the test methods and the test data elements.
For example, to test the +
operator, write:
@RunWith(Parameterized.class)
public class AdditionTest {
@Parameters(name = "{index}: {0} + {1} = {2}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { 0, 0, 0 }, { 1, 1, 2 },
{ 3, 2, 5 }, { 4, 3, 7 } });
}
private int firstSummand;
private int secondSummand;
private int sum;
public AdditionTest(int firstSummand, int secondSummand, int sum) {
this.firstSummand = firstSummand;
this.secondSummand = secondSummand;
this.sum = sum;
}
@Test
public void test() {
assertEquals(sum, firstSummand + secondSummand);
}
}
Each instance of AdditionTest
will be constructed using the three-argument constructor and the data values in the @Parameters
method.
In order that you can easily identify the individual tests, you may provide a name for the @Parameters
annotation. This name is allowed to contain placeholders, which are replaced at runtime. The placeholders are {index} the current parameter index {0} the first parameter value {1} the second parameter value ... ...
In the example given above, the Parameterized
runner creates names like [2: 3 + 2 = 5]
. If you don't use the name parameter, then the current parameter index is used as name.
You can also write:
@RunWith(Parameterized.class)
public class AdditionTest {
@Parameters(name = "{index}: {0} + {1} = {2}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { 0, 0, 0 }, { 1, 1, 2 },
{ 3, 2, 5 }, { 4, 3, 7 } });
}
@Parameter(0)
public int firstSummand;
@Parameter(1)
public int secondSummand;
@Parameter(2)
public int sum;
@Test
public void test() {
assertEquals(sum, firstSummand + secondSummand);
}
}
Each instance of AdditionTest
will be constructed with the default constructor and fields annotated by @Parameter
will be initialized with the data values in the @Parameters
method.
The parameters can be provided as an array, too:
@Parameters
public static Object[][] data() {
return new Object[][] { { 0, 0, 0 }, { 1, 1, 2 }, { 3, 2, 5 }, { 4, 3, 7 } } };
}
If your test needs a single parameter only, you don't have to wrap it with an array. Instead you can provide an Iterable
or an array of objects.
@Parameters
public static Iterable<? extends Object> data() {
return Arrays.asList("first test", "second test");
}
or
@Parameters
public static Object[] data() {
return new Object[] { "first test", "second test" };
}
If your test needs to perform some preparation or cleanup based on the parameters, this can be done by adding public static methods annotated with @BeforeParam/ @AfterParam. Such methods should either have no parameters or the same parameters as the test.
@BeforeParam
public static void beforeTestsForParameter(String onlyParameter) {
System.out.println("Testing " + onlyParameter);
}
By default the Parameterized runner creates a slightly modified BlockJUnit4ClassRunner for each set of parameters. You can build an own Parameterized runner that creates another runner for each set of parameters. Therefore you have to build a ParametersRunnerFactorythat creates a runner for each TestWithParameters. ( TestWithParameters are bundling the parameters and the test name.) The factory must have a public zero-arg constructor.
public class YourRunnerFactory implements ParametersRunnerFactory {
public Runner createRunnerForTestWithParameters(TestWithParameters test)
throws InitializationError {
return YourRunner(test);
}
}
Use the UseParametersRunnerFactory to tell the Parameterizedrunner that it should use your factory.
@RunWith(Parameterized.class)
@UseParametersRunnerFactory(YourRunnerFactory.class)
public class YourTest {
...
}
With org.junit.Assume you can dynamically skip tests. Assumptions are also supported by the @Parameters
method. Creating parameters is stopped when the assumption fails and none of the tests in the test class is executed. JUnit reports a Result#getAssumptionFailureCount() for the whole test class in this case.
@Parameters
public static Iterable<? extends Object> data() {
String os = System.getProperty("os.name").toLowerCase()
Assume.assumeTrue(os.contains("win"));
return Arrays.asList("first test", "second test");
}
[中]自定义运行程序Parameterized
实现参数化测试。运行参数化测试类时,会为测试方法和测试数据元素的叉积创建实例。
例如,要测试+
运算符,请编写:
@RunWith(Parameterized.class)
public class AdditionTest {
@Parameters(name = "{index}: {0} + {1} = {2}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { 0, 0, 0 }, { 1, 1, 2 },
{ 3, 2, 5 }, { 4, 3, 7 } });
}
private int firstSummand;
private int secondSummand;
private int sum;
public AdditionTest(int firstSummand, int secondSummand, int sum) {
this.firstSummand = firstSummand;
this.secondSummand = secondSummand;
this.sum = sum;
}
@Test
public void test() {
assertEquals(sum, firstSummand + secondSummand);
}
}
AdditionTest
的每个实例都将使用三参数构造函数和@Parameters
方法中的数据值来构造。
为了便于识别各个测试,可以为@Parameters
注释提供一个名称。此名称允许包含占位符,占位符在运行时被替换。占位符是{index}当前参数索引{0}第一个参数值{1}第二个参数值。。。
在上面给出的示例中,Parameterized
运行程序会创建类似[2: 3 + 2 = 5]
的名称。如果不使用name参数,则当前参数索引将用作name。
你也可以写:
@RunWith(Parameterized.class)
public class AdditionTest {
@Parameters(name = "{index}: {0} + {1} = {2}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { 0, 0, 0 }, { 1, 1, 2 },
{ 3, 2, 5 }, { 4, 3, 7 } });
}
@Parameter(0)
public int firstSummand;
@Parameter(1)
public int secondSummand;
@Parameter(2)
public int sum;
@Test
public void test() {
assertEquals(sum, firstSummand + secondSummand);
}
}
AdditionTest
的每个实例都将使用默认构造函数构造,由@Parameter
注释的字段将使用@Parameters
方法中的数据值初始化。
参数也可以作为数组提供:
@Parameters
public static Object[][] data() {
return new Object[][] { { 0, 0, 0 }, { 1, 1, 2 }, { 3, 2, 5 }, { 4, 3, 7 } } };
}
####单参数测试
如果你的测试只需要一个参数,你不需要用数组来包装它。相反,您可以提供一个Iterable
或一组对象。
@Parameters
public static Iterable<? extends Object> data() {
return Arrays.asList("first test", "second test");
}
或
@Parameters
public static Object[] data() {
return new Object[] { "first test", "second test" };
}
####在对特定参数执行测试之前/之后执行代码
如果测试需要根据参数执行一些准备或清理,可以通过添加带有@BeforeParam/@AfterParam注释的公共静态方法来完成。这种方法要么没有参数,要么与试验参数相同。
@BeforeParam
public static void beforeTestsForParameter(String onlyParameter) {
System.out.println("Testing " + onlyParameter);
}
####创造不同的跑步者
默认情况下,参数化的运行程序会为每组参数创建一个稍加修改的BlockJUnit4ClassRunner。可以构建自己的参数化运行程序,为每组参数创建另一个运行程序。因此,您必须构建一个ParametersRunnerFactory,为每个带有参数的测试创建一个运行程序。(TestWithParameters绑定了参数和测试名称。)工厂必须有一个公共零参数构造函数。
public class YourRunnerFactory implements ParametersRunnerFactory {
public Runner createRunnerForTestWithParameters(TestWithParameters test)
throws InitializationError {
return YourRunner(test);
}
}
使用UseParametersRunneFactory告诉ParameteredRunner它应该使用您的工厂。
@RunWith(Parameterized.class)
@UseParametersRunnerFactory(YourRunnerFactory.class)
public class YourTest {
...
}
####避免创建参数
与组织。朱尼特。假设您可以动态跳过测试。@Parameters
方法也支持假设。当假设失败且测试类中的所有测试均未执行时,将停止创建参数。在本例中,JUnit为整个测试类报告一个结果#getAssumptionFailureCount()。
@Parameters
public static Iterable<? extends Object> data() {
String os = System.getProperty("os.name").toLowerCase()
Assume.assumeTrue(os.contains("win"));
return Arrays.asList("first test", "second test");
}
代码示例来源:origin: neo4j/neo4j
@Parameters( name = "multiThreadedIndexPopulationEnabled = {0}" )
public static Object[] multiThreadedIndexPopulationEnabledValues()
{
return new Object[]{true, false};
}
代码示例来源:origin: google/j2objc
private void createRunnersForParameters(Iterable<Object[]> allParameters,
String namePattern) throws InitializationError, Exception {
try {
int i = 0;
for (Object[] parametersOfSingleTest : allParameters) {
String name = nameFor(namePattern, i, parametersOfSingleTest);
TestClassRunnerForParameters runner = new TestClassRunnerForParameters(
getTestClass().getJavaClass(), parametersOfSingleTest,
name);
runners.add(runner);
++i;
}
} catch (ClassCastException e) {
throw parametersMethodReturnedWrongType();
}
}
代码示例来源:origin: google/j2objc
/**
* Only called reflectively. Do not use programmatically.
*/
public Parameterized(Class<?> klass) throws Throwable {
super(klass, NO_RUNNERS);
Parameters parameters = getParametersMethod().getAnnotation(
Parameters.class);
createRunnersForParameters(allParameters(), parameters.name());
}
代码示例来源:origin: google/j2objc
@SuppressWarnings("unchecked")
private Iterable<Object[]> allParameters() throws Throwable {
Object parameters = getParametersMethod().invokeExplosively(null);
if (parameters instanceof Iterable) {
return (Iterable<Object[]>) parameters;
} else {
throw parametersMethodReturnedWrongType();
}
}
代码示例来源:origin: junit-team/junit4
private void validateBeforeParamAndAfterParamMethods(Integer parameterCount)
throws InvalidTestClassError {
List<Throwable> errors = new ArrayList<Throwable>();
validatePublicStaticVoidMethods(Parameterized.BeforeParam.class, parameterCount, errors);
validatePublicStaticVoidMethods(Parameterized.AfterParam.class, parameterCount, errors);
if (!errors.isEmpty()) {
throw new InvalidTestClassError(getTestClass().getJavaClass(), errors);
}
}
代码示例来源:origin: google/j2objc
private Exception parametersMethodReturnedWrongType() throws Exception {
String className = getTestClass().getName();
String methodName = getParametersMethod().getName();
String message = MessageFormat.format(
"{0}.{1}() must return an Iterable of arrays.",
className, methodName);
return new Exception(message);
}
代码示例来源:origin: com.impetus.fabric/fabric-jdbc-driver-shaded
/**
* Only called reflectively. Do not use programmatically.
*/
public Parameterized(Class<?> klass) throws Throwable {
super(klass, NO_RUNNERS);
ParametersRunnerFactory runnerFactory = getParametersRunnerFactory(
klass);
Parameters parameters = getParametersMethod().getAnnotation(
Parameters.class);
runners = Collections.unmodifiableList(createRunnersForParameters(
allParameters(), parameters.name(), runnerFactory));
}
代码示例来源:origin: google/j2objc
private List<FrameworkField> getAnnotatedFieldsByParameter() {
return getTestClass().getAnnotatedFields(Parameter.class);
}
代码示例来源:origin: org.ops4j.pax.tipi/org.ops4j.pax.tipi.junit
private TestWithParameters createTestWithNotNormalizedParameters(
String pattern, int index, Object parametersOrSingleParameter) {
Object[] parameters= (parametersOrSingleParameter instanceof Object[]) ? (Object[]) parametersOrSingleParameter
: new Object[] { parametersOrSingleParameter };
return createTestWithParameters(getTestClass(), pattern, index,
parameters);
}
代码示例来源:origin: com.impetus.fabric/fabric-jdbc-driver-shaded
private List<Runner> createRunnersForParameters(
Iterable<Object> allParameters, String namePattern,
ParametersRunnerFactory runnerFactory)
throws InitializationError,
Exception {
try {
List<TestWithParameters> tests = createTestsForParameters(
allParameters, namePattern);
List<Runner> runners = new ArrayList<Runner>();
for (TestWithParameters test : tests) {
runners.add(runnerFactory
.createRunnerForTestWithParameters(test));
}
return runners;
} catch (ClassCastException e) {
throw parametersMethodReturnedWrongType();
}
}
代码示例来源:origin: google/j2objc
private boolean fieldsAreAnnotated() {
return !getAnnotatedFieldsByParameter().isEmpty();
}
}
代码示例来源:origin: camunda/camunda-bpm-platform
private Exception parametersMethodReturnedWrongType() throws Exception {
String className = getTestClass().getName();
String methodName = getParametersMethod().getName();
String message = MessageFormat.format(
"{0}.{1}() must return an Iterable of arrays.",
className, methodName);
return new Exception(message);
}
代码示例来源:origin: camunda/camunda-bpm-platform
@SuppressWarnings("unchecked")
private Iterable<Object[]> allParameters() throws Throwable {
Object parameters = getParametersMethod().invokeExplosively(null);
if (parameters instanceof Iterable) {
return (Iterable<Object[]>) parameters;
} else {
throw parametersMethodReturnedWrongType();
}
}
代码示例来源:origin: org.ops4j.pax.tipi/org.ops4j.pax.tipi.junit
/**
* Only called reflectively. Do not use programmatically.
*/
public Parameterized(Class<?> klass) throws Throwable {
super(klass, NO_RUNNERS);
ParametersRunnerFactory runnerFactory = getParametersRunnerFactory(
klass);
Parameters parameters = getParametersMethod().getAnnotation(
Parameters.class);
runners = Collections.unmodifiableList(createRunnersForParameters(
allParameters(), parameters.name(), runnerFactory));
}
代码示例来源:origin: google/j2objc
private FrameworkMethod getParametersMethod() throws Exception {
List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(
Parameters.class);
for (FrameworkMethod each : methods) {
if (each.isStatic() && each.isPublic()) {
return each;
}
}
throw new Exception("No public static parameters method on class "
+ getTestClass().getName());
}
代码示例来源:origin: com.impetus.fabric/fabric-jdbc-driver-shaded
private TestWithParameters createTestWithNotNormalizedParameters(
String pattern, int index, Object parametersOrSingleParameter) {
Object[] parameters= (parametersOrSingleParameter instanceof Object[]) ? (Object[]) parametersOrSingleParameter
: new Object[] { parametersOrSingleParameter };
return createTestWithParameters(getTestClass(), pattern, index,
parameters);
}
代码示例来源:origin: org.ops4j.pax.tipi/org.ops4j.pax.tipi.junit
private List<Runner> createRunnersForParameters(
Iterable<Object> allParameters, String namePattern,
ParametersRunnerFactory runnerFactory)
throws InitializationError,
Exception {
try {
List<TestWithParameters> tests = createTestsForParameters(
allParameters, namePattern);
List<Runner> runners = new ArrayList<Runner>();
for (TestWithParameters test : tests) {
runners.add(runnerFactory
.createRunnerForTestWithParameters(test));
}
return runners;
} catch (ClassCastException e) {
throw parametersMethodReturnedWrongType();
}
}
代码示例来源:origin: camunda/camunda-bpm-platform
private boolean fieldsAreAnnotated() {
return !getAnnotatedFieldsByParameter().isEmpty();
}
}
代码示例来源:origin: neo4j/neo4j
@Parameters( name = "{0}" )
public static List<Class<? extends TransportConnection>> transports()
{
return asList( SocketConnection.class, WebSocketConnection.class, SecureSocketConnection.class, SecureWebSocketConnection.class );
}
代码示例来源:origin: camunda/camunda-bpm-platform
/**
* Only called reflectively. Do not use programmatically.
*/
public Parameterized(Class<?> klass) throws Throwable {
super(klass, NO_RUNNERS);
Parameters parameters = getParametersMethod().getAnnotation(
Parameters.class);
createRunnersForParameters(allParameters(), parameters.name());
}
内容来源于网络,如有侵权,请联系作者删除!