Best junit code snippet using org.junit.runners.Annotation Type Parameterized.Parameter
Source:CustomParameterized.java  
1/*2 * Hibernate, Relational Persistence for Idiomatic Java3 *4 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.5 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.6 */7package org.hibernate.testing.junit4;8import java.lang.annotation.Annotation;9import java.lang.annotation.ElementType;10import java.lang.annotation.Retention;11import java.lang.annotation.RetentionPolicy;12import java.lang.annotation.Target;13import java.lang.reflect.Field;14import java.text.MessageFormat;15import java.util.ArrayList;16import java.util.Arrays;17import java.util.Collections;18import java.util.List;19import java.util.SortedMap;20import java.util.TreeMap;21import org.junit.runner.Runner;22import org.junit.runner.manipulation.NoTestsRemainException;23import org.junit.runner.notification.RunNotifier;24import org.junit.runners.Parameterized;25import org.junit.runners.Suite;26import org.junit.runners.model.FrameworkField;27import org.junit.runners.model.FrameworkMethod;28import org.junit.runners.model.InitializationError;29import org.junit.runners.model.Statement;30/**31 * Allows the {@link CustomRunner} features in parameterized tests.32 * This is mostly copy-paste from {@link Parameterized} since the methods could not be overridden.33 *34 * The static {@link org.junit.BeforeClass} and {@link org.junit.AfterClass} methods will be executed35 * only once before and after all tests (since these should prepare static members).36 * Hibernate-specific {@link org.hibernate.testing.BeforeClassOnce} and {@link org.hibernate.testing.AfterClassOnce}37 * will be executed before and after each set of tests with given parameters.38 *39 * Class can override the parameters list (annotated by {@link org.junit.runners.Parameterized.Parameters}40 * by defining static method of the same name in inheriting class (this works although usually static41 * methods cannot override each other in Java).42 *43 * When there are multiple methods providing the parameters list, the used parameters list is a cross product44 * of all the options, concatenating the argument list according to {@link Order} values.45 *46 * Contrary to {@link Parameterized}, non-static parameters methods are allowed, but the test class needs47 * to have parameterless constructor, and therefore use {@link org.junit.runners.Parameterized.Parameter}48 * for setting these parameters. This allow type-safe overriding of the method; note that only the base49 * method needs the {@link org.junit.runners.Parameterized.Parameters} annotation, overriding methods50 * are invoked automatically.51 *52 * @author Radim Vansa <rvansa@redhat.com>53 */54public class CustomParameterized extends Suite {55	private static final List<Runner> NO_RUNNERS = Collections.emptyList();56	private final ArrayList<Runner> runners = new ArrayList<Runner>();57	/**58	 * Only called reflectively. Do not use programmatically.59	 */60	public CustomParameterized(Class<?> klass) throws Throwable {61		super(klass, NO_RUNNERS);62		List<FrameworkMethod> parametersMethods = getParametersMethods();63		createRunnersForParameters(allParameters(parametersMethods), concatNames(parametersMethods));64	}65	private String concatNames(List<FrameworkMethod> parametersMethods) {66		StringBuilder sb = new StringBuilder();67		for (FrameworkMethod method : parametersMethods) {68			Parameterized.Parameters parameters = method.getAnnotation(Parameterized.Parameters.class);69			if (sb.length() != 0) {70				sb.append(", ");71			}72			sb.append(parameters.name());73		}74		return sb.toString();75	}76	@Override77	protected List<Runner> getChildren() {78		return runners;79	}80	private Iterable<Object[]> allParameters(List<FrameworkMethod> parametersMethods) throws Throwable {81		ArrayList<Iterable<Object[]>> returnedParameters = new ArrayList<Iterable<Object[]>>();82		ArrayList<Object[]> allParameters = new ArrayList<Object[]>();83		Object cachedInstance = null;84		for (FrameworkMethod method : parametersMethods) {85			Object parameters;86			if (method.isStatic()) {87				parameters = method.invokeExplosively(null);88			}89			else {90				if (cachedInstance == null) {91					cachedInstance = getTestClass().getOnlyConstructor().newInstance();92				}93				parameters = method.invokeExplosively(cachedInstance);94			}95			if (parameters instanceof Iterable) {96				returnedParameters.add((Iterable<Object[]>) parameters);97			}98			else {99				throw parametersMethodReturnedWrongType(method);100			}101		}102		for (Iterable<Object[]> parameters : returnedParameters) {103			if (allParameters.isEmpty()) {104				for (Object[] array : parameters) {105					allParameters.add(array);106				}107			}108			else {109				ArrayList<Object[]> newAllParameters = new ArrayList<Object[]>();110				for (Object[] prev : allParameters) {111					for (Object[] array : parameters) {112						Object[] next = Arrays.copyOf(prev, prev.length + array.length);113						System.arraycopy(array, 0, next, prev.length, array.length);114						newAllParameters.add(next);115					}116				}117				allParameters = newAllParameters;118			}119		}120		return allParameters;121	}122	private List<FrameworkMethod> getParametersMethods() throws Exception {123		List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(124				Parameterized.Parameters.class);125		SortedMap<Integer, FrameworkMethod> sortedMethods = new TreeMap<Integer, FrameworkMethod>();126		for (FrameworkMethod each : methods) {127			if (each.isPublic()) {128				if (!each.isStatic()) {129					if (getTestClass().getOnlyConstructor().getParameterCount() != 0) {130						throw new Exception("Method " + each.getMethod() + " is annotated with @Parameters, it is not static and there is no parameter-less constructor!");131					}132				}133				Order order = each.getAnnotation(Order.class);134				int value = order == null ? 0 : order.value();135				FrameworkMethod prev = sortedMethods.put(value, each);136				if (prev != null) {137					throw new Exception(String.format("There are more methods annotated with @Parameters and @Order(value=%d): %s (%s) and %s (%s)",138							value, prev.getMethod(), prev.getAnnotation(Order.class), each.getMethod(), order));139				}140			}141			else {142				throw new Exception("Method " + each.getMethod() + " is annotated with @Parameters but it is not public!");143			}144		}145		if (sortedMethods.isEmpty()) {146			throw new Exception("No public static parameters method on class "147					+ getTestClass().getName());148		}149		return new ArrayList<FrameworkMethod>(sortedMethods.values());150	}151	private void createRunnersForParameters(Iterable<Object[]> allParameters, String namePattern) throws Exception {152		int i = 0;153		for (Object[] parametersOfSingleTest : allParameters) {154			String name = nameFor(namePattern, i, parametersOfSingleTest);155			CustomRunnerForParameters runner = new CustomRunnerForParameters(156					getTestClass().getJavaClass(), parametersOfSingleTest,157					name);158			runners.add(runner);159			++i;160		}161	}162	private String nameFor(String namePattern, int index, Object[] parameters) {163		String finalPattern = namePattern.replaceAll("\\{index\\}",164				Integer.toString(index));165		String name = MessageFormat.format(finalPattern, parameters);166		return "[" + name + "]";167	}168	private Exception parametersMethodReturnedWrongType(FrameworkMethod method) throws Exception {169		String className = getTestClass().getName();170		String methodName = method.getName();171		String message = MessageFormat.format(172				"{0}.{1}() must return an Iterable of arrays.",173				className, methodName);174		return new Exception(message);175	}176	private List<FrameworkField> getAnnotatedFieldsByParameter() {177		return getTestClass().getAnnotatedFields(Parameterized.Parameter.class);178	}179	private boolean fieldsAreAnnotated() {180		return !getAnnotatedFieldsByParameter().isEmpty();181	}182	private class CustomRunnerForParameters extends CustomRunner {183		private final Object[] parameters;184		private final String name;185		CustomRunnerForParameters(Class<?> type, Object[] parameters, String name) throws InitializationError, NoTestsRemainException {186			super(type);187			this.parameters = parameters;188			this.name = name;189		}190		@Override191		protected Object getTestInstance() throws Exception {192			if (testInstance == null) {193				if (fieldsAreAnnotated()) {194					testInstance = createTestUsingFieldInjection();195				}196				else {197					testInstance = createTestUsingConstructorInjection();198				}199			}200			return testInstance;201		}202		private Object createTestUsingConstructorInjection() throws Exception {203			return getTestClass().getOnlyConstructor().newInstance(parameters);204		}205		private Object createTestUsingFieldInjection() throws Exception {206			List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();207			if (annotatedFieldsByParameter.size() != parameters.length) {208				throw new Exception("Wrong number of parameters and @Parameter fields." +209						" @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + parameters.length + ".");210			}211			Object testClassInstance = getTestClass().getJavaClass().newInstance();212			for (FrameworkField each : annotatedFieldsByParameter) {213				Field field = each.getField();214				Parameterized.Parameter annotation = field.getAnnotation(Parameterized.Parameter.class);215				int index = annotation.value();216				try {217					field.set(testClassInstance, parameters[index]);218				}219				catch (IllegalArgumentException iare) {220					throw new Exception(getTestClass().getName() + ": Trying to set " + field.getName() +221							" with the value " + parameters[index] +222							" that is not the right type (" + parameters[index].getClass().getSimpleName() + " instead of " +223							field.getType().getSimpleName() + ").", iare);224				}225			}226			return testClassInstance;227		}228		@Override229		protected String getName() {230			return name;231		}232		@Override233		protected String testName(FrameworkMethod method) {234			return method.getName() + getName();235		}236		@Override237		protected void validateConstructor(List<Throwable> errors) {238			validateOnlyOneConstructor(errors);239			if (fieldsAreAnnotated()) {240				validateZeroArgConstructor(errors);241			}242		}243		@Override244		protected void validateFields(List<Throwable> errors) {245			super.validateFields(errors);246			if (fieldsAreAnnotated()) {247				List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();248				int[] usedIndices = new int[annotatedFieldsByParameter.size()];249				for (FrameworkField each : annotatedFieldsByParameter) {250					int index = each.getField().getAnnotation(Parameterized.Parameter.class).value();251					if (index < 0 || index > annotatedFieldsByParameter.size() - 1) {252						errors.add(253								new Exception("Invalid @Parameter value: " + index + ". @Parameter fields counted: " +254										annotatedFieldsByParameter.size() + ". Please use an index between 0 and " +255										(annotatedFieldsByParameter.size() - 1) + ".")256						);257					}258					else {259						usedIndices[index]++;260					}261				}262				for (int index = 0; index < usedIndices.length; index++) {263					int numberOfUse = usedIndices[index];264					if (numberOfUse == 0) {265						errors.add(new Exception("@Parameter(" + index + ") is never used."));266					}267					else if (numberOfUse > 1) {268						errors.add(new Exception("@Parameter(" + index + ") is used more than once (" + numberOfUse + ")."));269					}270				}271			}272		}273		@Override274		protected Statement classBlock(RunNotifier notifier) {275			Statement statement = childrenInvoker(notifier);276			statement = withBeforeClasses(statement);277			statement = withAfterClasses(statement);278			// no class rules executed! These will be executed for the whole suite.279			return statement;280		}281		@Override282		protected Statement withBeforeClasses(Statement statement) {283			if ( isAllTestsIgnored() ) {284				return statement;285			}286			return new BeforeClassCallbackHandler( this, statement );287		}288		@Override289		protected Statement withAfterClasses(Statement statement) {290			if ( isAllTestsIgnored() ) {291				return statement;292			}293			return new AfterClassCallbackHandler( this, statement );294		}295		@Override296		protected Annotation[] getRunnerAnnotations() {297			return new Annotation[0];298		}299	}300	@Retention(value = RetentionPolicy.RUNTIME)301	@Target(ElementType.METHOD)302	public @interface Order {303		int value();304	}305}...Source:SpringRunnerWithParameters.java  
1package com.github.ahunigel.test.junit.runner;2import org.junit.runner.notification.RunNotifier;3import org.junit.runners.Parameterized;4import org.junit.runners.model.FrameworkField;5import org.junit.runners.model.FrameworkMethod;6import org.junit.runners.model.InitializationError;7import org.junit.runners.model.Statement;8import org.junit.runners.parameterized.TestWithParameters;9import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;10import java.lang.annotation.Annotation;11import java.lang.reflect.Field;12import java.util.List;13/**14 * A {@link org.springframework.test.context.junit4.SpringRunner} with parameters support. Parameters can be15 * injected via constructor or into annotated fields.16 * <p>17 * Created by nigel on 2020/3/22.18 *19 * @author nigel20 */21public class SpringRunnerWithParameters extends SpringJUnit4ClassRunner {22  private final Object[] parameters;23  private final String name;24  public SpringRunnerWithParameters(TestWithParameters test) throws InitializationError {25    super(test.getTestClass().getJavaClass());26    parameters = test.getParameters().toArray(27        new Object[test.getParameters().size()]);28    name = test.getName();29  }30  @Override31  public Object createTest() throws Exception {32    Object testInstance;33    if (fieldsAreAnnotated()) {34      testInstance = createTestUsingFieldInjection();35    } else {36      testInstance = createTestUsingConstructorInjection();37    }38    getTestContextManager().prepareTestInstance(testInstance);39    return testInstance;40  }41  private Object createTestUsingConstructorInjection() throws Exception {42    return getTestClass().getOnlyConstructor().newInstance(parameters);43  }44  private Object createTestUsingFieldInjection() throws Exception {45    List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();46    if (annotatedFieldsByParameter.size() != parameters.length) {47      throw new Exception(48          "Wrong number of parameters and @Parameter fields."49              + " @Parameter fields counted: "50              + annotatedFieldsByParameter.size()51              + ", available parameters: " + parameters.length52              + ".");53    }54    Object testClassInstance = getTestClass().getJavaClass().newInstance();55    for (FrameworkField each : annotatedFieldsByParameter) {56      Field field = each.getField();57      Parameterized.Parameter annotation = field.getAnnotation(Parameterized.Parameter.class);58      int index = annotation.value();59      try {60        field.set(testClassInstance, parameters[index]);61      } catch (IllegalArgumentException iare) {62        throw new Exception(getTestClass().getName()63            + ": Trying to set " + field.getName()64            + " with the value " + parameters[index]65            + " that is not the right type ("66            + parameters[index].getClass().getSimpleName()67            + " instead of " + field.getType().getSimpleName()68            + ").", iare);69      }70    }71    return testClassInstance;72  }73  @Override74  protected String getName() {75    return name;76  }77  @Override78  protected String testName(FrameworkMethod method) {79    return method.getName() + getName();80  }81  @Override82  protected void validateConstructor(List<Throwable> errors) {83    validateOnlyOneConstructor(errors);84    if (fieldsAreAnnotated()) {85      validateZeroArgConstructor(errors);86    }87  }88  @Override89  protected void validateFields(List<Throwable> errors) {90    super.validateFields(errors);91    if (fieldsAreAnnotated()) {92      List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();93      int[] usedIndices = new int[annotatedFieldsByParameter.size()];94      for (FrameworkField each : annotatedFieldsByParameter) {95        int index = each.getField().getAnnotation(Parameterized.Parameter.class)96            .value();97        if (index < 0 || index > annotatedFieldsByParameter.size() - 1) {98          errors.add(new Exception("Invalid @Parameter value: "99              + index + ". @Parameter fields counted: "100              + annotatedFieldsByParameter.size()101              + ". Please use an index between 0 and "102              + (annotatedFieldsByParameter.size() - 1) + "."));103        } else {104          usedIndices[index]++;105        }106      }107      for (int index = 0; index < usedIndices.length; index++) {108        int numberOfUse = usedIndices[index];109        if (numberOfUse == 0) {110          errors.add(new Exception("@Parameter(" + index111              + ") is never used."));112        } else if (numberOfUse > 1) {113          errors.add(new Exception("@Parameter(" + index114              + ") is used more than once (" + numberOfUse + ")."));115        }116      }117    }118  }119  @Override120  protected Statement classBlock(RunNotifier notifier) {121    return childrenInvoker(notifier);122  }123  @Override124  protected Annotation[] getRunnerAnnotations() {125    return new Annotation[0];126  }127  private List<FrameworkField> getAnnotatedFieldsByParameter() {128    return getTestClass().getAnnotatedFields(Parameterized.Parameter.class);129  }130  private boolean fieldsAreAnnotated() {131    return !getAnnotatedFieldsByParameter().isEmpty();132  }133}...Source:AbstractParameterizedHazelcastClassRunner.java  
1/*2 * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.3 *4 *  Licensed under the Apache License, Version 2.0 (the "License");5 *  you may not use this file except in compliance with the License.6 *  You may obtain a copy of the License at7 *8 *  http://www.apache.org/licenses/LICENSE-2.09 *10 *  Unless required by applicable law or agreed to in writing, software11 *  distributed under the License is distributed on an "AS IS" BASIS,12 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 *  See the License for the specific language governing permissions and14 *  limitations under the License.15 */16package com.hazelcast.test;17import java.lang.annotation.Annotation;18import java.lang.reflect.Field;19import java.util.List;20import org.junit.runner.notification.RunNotifier;21import org.junit.runners.BlockJUnit4ClassRunner;22import org.junit.runners.Parameterized;23import org.junit.runners.model.FrameworkField;24import org.junit.runners.model.FrameworkMethod;25import org.junit.runners.model.InitializationError;26import org.junit.runners.model.Statement;27/**28 * A base test runner which has an ability to run parameterized tests.29 */30public abstract class AbstractParameterizedHazelcastClassRunner extends BlockJUnit4ClassRunner {31    protected boolean isParameterized;32    protected Object[] fParameters;33    protected String fName;34    /**35     * Creates a BlockJUnit4ClassRunner to run {@code klass}36     *37     * @param klass38     * @throws org.junit.runners.model.InitializationError if the test class is malformed.39     */40    public AbstractParameterizedHazelcastClassRunner(Class<?> klass) throws InitializationError {41        super(klass);42    }43    public AbstractParameterizedHazelcastClassRunner(Class<?> klass, Object[] parameters,44                                                     String name) throws InitializationError {45        super(klass);46        fParameters = parameters;47        fName = name;48    }49    @Override50    protected String getName() {51        if (isParameterized) {52            return fName;53        } else {54            return super.getName();55        }56    }57    @Override58    protected String testName(FrameworkMethod method) {59        if (isParameterized) {60            return method.getName() + getName();61        } else {62            return method.getName();63        }64    }65    public void setParameterized(boolean isParameterized) {66        this.isParameterized = isParameterized;67    }68    @Override69    public Object createTest() throws Exception {70        if (isParameterized) {71            if (fieldsAreAnnotated()) {72                return createTestUsingFieldInjection();73            } else {74                return createTestUsingConstructorInjection();75            }76        }77        return super.createTest();78    }79    private Object createTestUsingConstructorInjection() throws Exception {80        return getTestClass().getOnlyConstructor().newInstance(fParameters);81    }82    private Object createTestUsingFieldInjection() throws Exception {83        List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();84        if (annotatedFieldsByParameter.size() != fParameters.length) {85            throw new Exception("Wrong number of parameters and @Parameter fields." +86                    " @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + fParameters.length + ".");87        }88        Object testClassInstance = getTestClass().getJavaClass().newInstance();89        for (FrameworkField each : annotatedFieldsByParameter) {90            Field field = each.getField();91            Parameterized.Parameter annotation = field.getAnnotation(Parameterized.Parameter.class);92            int index = annotation.value();93            try {94                field.set(testClassInstance, fParameters[index]);95            } catch (IllegalArgumentException iare) {96                throw new Exception(getTestClass().getName() + ": Trying to set " + field.getName() +97                        " with the value " + fParameters[index] +98                        " that is not the right type (" + fParameters[index].getClass().getSimpleName() + " instead of " +99                        field.getType().getSimpleName() + ").", iare);100            }101        }102        return testClassInstance;103    }104    private boolean fieldsAreAnnotated() {105        return !getAnnotatedFieldsByParameter().isEmpty();106    }107    private List<FrameworkField> getAnnotatedFieldsByParameter() {108        return getTestClass().getAnnotatedFields(Parameterized.Parameter.class);109    }110    @Override111    protected Statement classBlock(RunNotifier notifier) {112        if (isParameterized) {113            return childrenInvoker(notifier);114        } else {115            return super.classBlock(notifier);116        }117    }118    @Override119    protected Annotation[] getRunnerAnnotations() {120        return new Annotation[0];121    }122}...Source:BlockJUnit4ClassRunnerWithParameters.java  
1package org.junit.runners.parameterized;2import java.lang.annotation.Annotation;3import java.lang.reflect.Constructor;4import java.lang.reflect.Field;5import java.util.List;6import org.junit.runner.notification.RunNotifier;7import org.junit.runners.BlockJUnit4ClassRunner;8import org.junit.runners.Parameterized.Parameter;9import org.junit.runners.model.FrameworkField;10import org.junit.runners.model.FrameworkMethod;11import org.junit.runners.model.InitializationError;12import org.junit.runners.model.Statement;13import org.junit.runners.model.TestClass;14public class BlockJUnit4ClassRunnerWithParameters15  extends BlockJUnit4ClassRunner16{17  private final Object[] parameters;18  private final String name;19  20  public BlockJUnit4ClassRunnerWithParameters(TestWithParameters test)21    throws InitializationError22  {23    super(test.getTestClass().getJavaClass());24    parameters = test.getParameters().toArray(new Object[test.getParameters().size()]);25    26    name = test.getName();27  }28  29  public Object createTest() throws Exception30  {31    if (fieldsAreAnnotated()) {32      return createTestUsingFieldInjection();33    }34    return createTestUsingConstructorInjection();35  }36  37  private Object createTestUsingConstructorInjection() throws Exception38  {39    return getTestClass().getOnlyConstructor().newInstance(parameters);40  }41  42  private Object createTestUsingFieldInjection() throws Exception {43    List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();44    if (annotatedFieldsByParameter.size() != parameters.length) {45      throw new Exception("Wrong number of parameters and @Parameter fields. @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + parameters.length + ".");46    }47    48    Object testClassInstance = getTestClass().getJavaClass().newInstance();49    for (FrameworkField each : annotatedFieldsByParameter) {50      Field field = each.getField();51      Parameterized.Parameter annotation = (Parameterized.Parameter)field.getAnnotation(Parameterized.Parameter.class);52      int index = annotation.value();53      try {54        field.set(testClassInstance, parameters[index]);55      } catch (IllegalArgumentException iare) {56        throw new Exception(getTestClass().getName() + ": Trying to set " + field.getName() + " with the value " + parameters[index] + " that is not the right type (" + parameters[index].getClass().getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare);57      }58    }59    60    return testClassInstance;61  }62  63  protected String getName()64  {65    return name;66  }67  68  protected String testName(FrameworkMethod method)69  {70    return method.getName() + getName();71  }72  73  protected void validateConstructor(List<Throwable> errors)74  {75    validateOnlyOneConstructor(errors);76    if (fieldsAreAnnotated()) {77      validateZeroArgConstructor(errors);78    }79  }80  81  protected void validateFields(List<Throwable> errors)82  {83    super.validateFields(errors);84    if (fieldsAreAnnotated()) {85      List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();86      int[] usedIndices = new int[annotatedFieldsByParameter.size()];87      for (FrameworkField each : annotatedFieldsByParameter) {88        int index = ((Parameterized.Parameter)each.getField().getAnnotation(Parameterized.Parameter.class)).value();89        90        if ((index < 0) || (index > annotatedFieldsByParameter.size() - 1)) {91          errors.add(new Exception("Invalid @Parameter value: " + index + ". @Parameter fields counted: " + annotatedFieldsByParameter.size() + ". Please use an index between 0 and " + (annotatedFieldsByParameter.size() - 1) + "."));92        }93        else94        {95          usedIndices[index] += 1;96        }97      }98      for (int index = 0; index < usedIndices.length; index++) {99        int numberOfUse = usedIndices[index];100        if (numberOfUse == 0) {101          errors.add(new Exception("@Parameter(" + index + ") is never used."));102        }103        else if (numberOfUse > 1) {104          errors.add(new Exception("@Parameter(" + index + ") is used more than once (" + numberOfUse + ")."));105        }106      }107    }108  }109  110  protected Statement classBlock(RunNotifier notifier)111  {112    return childrenInvoker(notifier);113  }114  115  protected Annotation[] getRunnerAnnotations()116  {117    return new Annotation[0];118  }119  120  private List<FrameworkField> getAnnotatedFieldsByParameter() {121    return getTestClass().getAnnotatedFields(Parameterized.Parameter.class);122  }123  124  private boolean fieldsAreAnnotated() {125    return !getAnnotatedFieldsByParameter().isEmpty();126  }127}...Annotation Type Parameterized.Parameter
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.junit.runners.Parameterized;4import org.junit.runners.Parameterized.Parameters;5import java.util.Arrays;6import java.util.Collection;7@RunWith(Parameterized.class)8public class ParameterizedTest {9    private int number;10    public ParameterizedTest(int number) {11        this.number = number;12    }13    public static Collection<Object[]> data() {14        Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }, { 7 } };15        return Arrays.asList(data);16    }17    public void test() {18        System.out.println("Parameterized Number is : " + number);19    }20}21import org.junit.Test;22import org.junit.runner.RunWith;23import org.junit.runners.Parameterized;24import java.util.Arrays;25import java.util.Collection;26@RunWith(Parameterized.class)27public class ParameterizedTest {28    private int number;29    public ParameterizedTest(int number) {30        this.number = number;31    }32    public static Collection<Object[]> data() {33        Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }, { 7 } };34        return Arrays.asList(data);35    }36    public void test() {37        System.out.println("Parameterized Number is : " + number);38    }39}Annotation Type Parameterized.Parameter
Using AI Code Generation
1@RunWith(Parameterized.class)2public class JUnitParameterizedTest {3    private int number;4    public JUnitParameterizedTest(int number) {5        this.number = number;6    }7    public static Collection<Object[]> data() {8        Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 }, { 5 } };9        return Arrays.asList(data);10    }11    public void test() {12        assertTrue(number > 0 && number < 6);13    }14}15@RunWith(Parameterized.class)16public class JUnitParameterizedTest {17    private int number;18    private String str;19    public JUnitParameterizedTest(int number, String str) {20        this.number = number;21        this.str = str;22    }23    public static Collection<Object[]> data() {24        Object[][] data = new Object[][] { { 1, "one" }, { 2, "two" }, { 3, "three" }, { 4, "four" }, { 5, "five" } };25        return Arrays.asList(data);26    }27    public void test() {28        assertTrue(number > 0 && number < 6);29    }30}31@RunWith(Parameterized.class)32public class JUnitParameterizedTest {33    private int number;Annotation Type Parameterized.Parameter
Using AI Code Generation
1package org.junit.runners;2import java.lang.annotation.ElementType;3import java.lang.annotation.Retention;4import java.lang.annotation.RetentionPolicy;5import java.lang.annotation.Target;6import org.junit.runner.RunWith;7import org.junit.runners.Parameterized;8@Retention(RetentionPolicy.RUNTIME)9@Target(ElementType.PARAMETER)10public @interface Parameter {11}12package org.junit.runners;13import java.lang.annotation.ElementType;14import java.lang.annotation.Retention;15import java.lang.annotation.RetentionPolicy;16import java.lang.annotation.Target;17import org.junit.runner.RunWith;18import org.junit.runners.Parameterized;19@Retention(RetentionPolicy.RUNTIME)20@Target(ElementType.METHOD)21public @interface Parameters {22}23package org.junit.runners;24import java.lang.annotation.ElementType;25import java.lang.annotation.Retention;26import java.lang.annotation.RetentionPolicy;27import java.lang.annotation.Target;28import org.junit.runner.RunWith;29import org.junit.runners.Parameterized;30@Retention(RetentionPolicy.RUNTIME)31@Target(ElementType.TYPE)32public @interface UseParametersRunnerFactory {33}34package org.junit.runners;35import java.lang.annotation.ElementType;36import java.lang.annotation.Retention;37import java.lang.annotation.RetentionPolicy;38import java.lang.annotation.Target;39import org.junit.runner.RunWith;40import org.junit.runners.Parameterized;41@Retention(RetentionPolicy.RUNTIME)42@Target(ElementType.TYPE)43public @interface UseParametersRunnerFactory {44}45package org.junit.runners;46import java.lang.annotation.ElementType;47import java.lang.annotation.Retention;48import java.lang.annotation.RetentionPolicy;49import java.lang.annotation.Target;50import org.junit.runner.RunWith;51import org.junit.runners.Parameterized;52@Retention(RetentionPolicy.RUNTIME)53@Target(ElementType.TYPE)54public @interface UseParametersRunnerFactory {55}56package org.junit.runners;57import java.lang.annotation.ElementType;58import java.lang.annotation.Retention;59import java.lang.annotation.RetentionPolicy;60import java.lang.annotation.Target;61import org.junit.runner.RunWith;62import org.junit.runners.Parameterized;63@Retention(RetentionPolicy.RUNTIMEAnnotation Type Parameterized.Parameter
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestClass {3    public static Collection<Object[]> data() {4        return Arrays.asList(new Object[][] { { 1, 2 }, { 3, 4 }, { 5, 6 } });5    }6    private int fInput;7    private int fExpected;8    public TestClass(int input, int expected) {9        fInput = input;10        fExpected = expected;11    }12    @Parameterized.Parameter(0)13    public int fInput;14    @Parameterized.Parameter(1)15    public int fExpected;16    @Parameterized.Parameter(value = 0)17    public int fInput;18    @Parameterized.Parameter(value = 1)19    public int fExpected;20    public void test() {21        assertEquals(fExpected, fInput);22    }23}24public static Collection<Object[]> data() {25    return Arrays.asList(new Object[][] { { 1, 2 }, { 3, 4 }, { 5, 6 } });26}27@Parameter(0)28public int fInput;29@Parameter(1)30public int fExpected;31@Parameter(value = 0)32public int fInput;33@Parameter(value = 1)34public int fExpected;35public void test() {36    assertEquals(fExpected, fInput);37}38public static Collection<Object[]> data() {39    return Arrays.asList(new Object[][] { { 1, 2 }, { 3, 4 }, { 5, 6 }Annotation Type Parameterized.Parameter
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestClass{3    @Parameterized.Parameter(0)4    public String input;5    @Parameterized.Parameter(1)6    public String expected;7    public static Collection<Object[]> data() {8        return Arrays.asList(new Object[][] {{"input1", "expected1"}, {"input2", "expected2"}});9    }10    public void testMethod(){11    }12}13@RunWith(Parameterized.class)14public class TestClass{15    private String input;16    private String expected;17    public TestClass(String input, String expected){18        this.input = input;19        this.expected = expected;20    }21    public static Collection<Object[]> data() {22        return Arrays.asList(new Object[][] {{"input1", "expected1"}, {"input2", "expected2"}});23    }24    public void testMethod(){25    }26}27@RunWith(Parameterized.class)28public class TestClass{29    private String input;30    private String expected;31    public TestClass(String input, String expected){32        this.input = input;33        this.expected = expected;34    }35    public static Collection<Object[]> data() {36        return Arrays.asList(new Object[][] {{"input1", "expected1"}, {"input2", "expected2"}});37    }38    public void testMethod(){39    }40}41@RunWith(Parameterized.class)42public class TestClass{43    private String input;44    private String expected;45    public TestClass(String input, String expected){46        this.input = input;47        this.expected = expected;48    }49    public static Collection<Object[]> data() {50        return Arrays.asList(new Object[][] {{"input1", "expected1"}, {"input2", "expected2"}});51    }52    public void testMethod(){53    }54}Annotation Type Parameterized.Parameter
Using AI Code Generation
1package com.javacodegeeks.junit;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.junit.runners.Parameterized;5import org.junit.runners.Parameterized.Parameter;6import org.junit.runners.Parameterized.Parameters;7import java.util.Arrays;8import java.util.Collection;9import static org.junit.Assert.assertEquals;10@RunWith(Parameterized.class)11public class ParameterizedTest {12    @Parameter(0)13    public int firstNumber;14    @Parameter(1)15    public int secondNumber;16    public static Collection<Object[]> data() {17        Object[][] data = new Object[][] { { 1, 2 }, { 5, 3 }, { 121, 4 } };18        return Arrays.asList(data);19    }20    public void testAdd() {21        System.out.println("Sum of " + firstNumber + " and " + secondNumber + " is " + (firstNumber + secondNumber));22        assertEquals(firstNumber + secondNumber, 3);23    }24}25package com.javacodegeeks.junit;26import org.junit.Test;27import org.junit.runner.RunWith;28import org.junit.runners.Parameterized;29import org.junit.runners.Parameterized.Parameters;30import java.util.Arrays;31import java.util.Collection;32import static org.junit.Assert.assertEquals;33@RunWith(Parameterized.class)34public class ParameterizedTest {35    private int firstNumber;36    private int secondNumber;37    public ParameterizedTest(int firstNumber, int secondNumber) {38        this.firstNumber = firstNumber;39        this.secondNumber = secondNumber;40    }41    public static Collection<Object[]> data() {42        Object[][] data = new Object[][] { { 1, 2 }, { 5, 3 }, { 121, 4 } };43        return Arrays.asList(data);44    }45    public void testAdd() {46        System.out.println("Sum of " + firstNumber + " and " + secondNumber + " is " + (firstNumber + secondNumber));47        assertEquals(firstNumber + secondNumber, 3);48    }49}Annotation Type Parameterized.Parameter
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestClass {3	private int number;4	private int expected;5	public TestClass(int number, int expected) {6		this.number = number;7		this.expected = expected;8	}9	public static Collection<Object[]> data() {10		Collection<Object[]> data = new ArrayList<>();11		data.add(new Object[] {1, 1});12		data.add(new Object[] {2, 2});13		data.add(new Object[] {3, 6});14		data.add(new Object[] {4, 24});15		data.add(new Object[] {5, 120});16		return data;17	}18	public void test() {19		Factorial factorial = new Factorial();20		int actual = factorial.factorial(number);21		assertEquals(expected, actual);22	}23}24public class Factorial {25	public int factorial(int number) {26		if (number == 0) {27			return 1;28		} else {29			return number * factorial(number - 1);30		}31	}32}33In the above code, we declare a class that will contain the test method. We annotate the class with @RunWith(Parameterized.class) to indicate that we will use Parameterized test. We declare a variable to store the data that will be passed to the test method. We declare a constructor that will receive the data from the collection of data. We declare a method that will return collection of data. We annotate the method with @Parameters. We create aLambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!
