Best junit code snippet using org.junit.runners.Annotation Type Parameterized.Parameters
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:AddTest.java  
1package company.annotion;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.junit.runners.Parameterized;5import org.junit.runners.model.FrameworkMember;6import org.junit.runners.model.FrameworkMethod;7import java.lang.annotation.Annotation;8import java.lang.reflect.Method;9import java.util.*;10import static org.junit.Assert.assertEquals;11@RunWith(Parameterized.class)12public class AddTest {13    private static Calculator calculator = new Calculator();14    private int param;15    private int param1;16    private int result;17    public AddTest(int param,int param1, int result){18        this.param  = param;19        this.result = result;20        this.param1  = param1;21    }22    @Parameterized.Parameters23    public Collection da(){24        return Arrays.asList(new Object[][]{25                {1,2,3},26                {1,3,4},27                {1,4,5},28        });29    }30     @Test31    public void addTest(){32        calculator.add(param, param1);33        assertEquals(result,calculator.getResult());34    }35    @Test(expected = ArithmeticException.class) //妿ä¸å è¿ä¸ªï¼ä¼æåºå¼å¸¸ï¼java.lang.ArithmeticException: / by zeroï¼ç¨ä¾ä¸éè¿36    public void divideByZero(){37        calculator.divide(0);38    }39    public static Method[] getMethod(){40//        Method[] methods = AddTest.class.getDeclaredMethods();41//        Annotation[] annotations = AddTest.class.getAnnotations();42//        Parameterized.Parameters annotation = (Parameterized.Parameters.class);43//44//        Method[] me = annotation.annotationType().getDeclaredMethods();45//        AddTest anno = AddTest.class.getAnnotation(Test.class);46//47//        Method[] met = anno.annotationType().getDeclaredMethods();48//        if(anno != null){49//            Method[] met = anno.annotationType().getDeclaredMethods();50        return null;51    }52    public static void main(){53    }54}...Annotation Type Parameterized.Parameters
Using AI Code Generation
1import org.junit.runner.RunWith;2import org.junit.runners.Parameterized;3import org.junit.runners.Parameterized.Parameters;4import org.junit.runners.Parameterized.Parameter;5@RunWith(Parameterized.class)6public class TestClass {7    @Parameters(name = "{index}: fib({0})={1}")8    public static Iterable<Object[]> data() {9        return Arrays.asList(new Object[][] {10            { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }11        });12    }13    @Parameter(value = 0)14    public int fInput;15    @Parameter(value = 1)16    public int fExpected;17    public void test() {18        assertEquals(fExpected, fib(fInput));19    }20    private int fib(int n) {21        if (n == 0) return 0;22        if (n == 1) return 1;23        return fib(n - 1) + fib(n - 2);24    }25}260: fib(0)=0271: fib(1)=1282: fib(2)=1293: fib(3)=2304: fib(4)=3315: fib(5)=5326: fib(6)=833import org.junit.runner.RunWith;34import org.junit.runners.Parameterized;35import org.junit.runners.Parameterized.Parameters;36import org.junit.runners.Parameterized.Parameter;37@RunWith(Parameterized.class)38public class TestClass {39    @Parameters(name = "{index}: fib({0})={1}")40    public static Object[][] data() {41        return new Object[][] {42            { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4Annotation Type Parameterized.Parameters
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestJunit {3    private int number;4    public TestJunit(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        System.out.println("Parameterized Number is : " + number);13    }14}15import java.util.Arrays;16import java.util.Collection;17import org.junit.Test;18import org.junit.runner.RunWith;19import org.junit.runners.Parameterized;20import org.junit.runners.Parameterized.Parameters;21@RunWith(Parameterized.class)22public class TestJunit {23    private String str;24    public TestJunit(String str) {25        this.str = str;26    }27    public static Collection<String[]> data() {28        String[][] data = new String[][] { { "t1" }, { "t2" } };29        return Arrays.asList(data);30    }31    public void test() {32        System.out.println("Parameterized String is : " + str);33    }34}35import java.util.Arrays;36import java.util.Collection;37import org.junit.Test;38import org.junit.runner.RunWith;39import org.junit.runners.Parameterized;40import org.junit.runners.Parameterized.Parameters;LambdaTest 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!!
