Best junit code snippet using org.junit.runners.Annotation Type Parameterized.UseParametersRunnerFactory
Source:SuiteWithParameters.java  
1/*2 * Copyright 2015 Hartmut Jürgens3 *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 de.juergens.util;17import org.junit.Ignore;18import org.junit.runner.Description;19import org.junit.runner.Runner;20import org.junit.runner.notification.RunNotifier;21import org.junit.runners.Parameterized;22import org.junit.runners.ParentRunner;23import org.junit.runners.Suite;24import org.junit.runners.model.FrameworkMethod;25import org.junit.runners.model.InitializationError;26import org.junit.runners.model.TestClass;27import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;28import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory;29import org.junit.runners.parameterized.ParametersRunnerFactory;30import org.junit.runners.parameterized.TestWithParameters;31import java.io.File;32import java.io.InputStream;33import java.lang.annotation.*;34import java.net.URISyntaxException;35import java.nio.file.Path;36import java.nio.file.Paths;37import java.text.MessageFormat;38import java.util.*;39@Ignore40public class SuiteWithParameters extends ParentRunner<Suite> {41    private final Class<?> testClass;42    private final Path rootPath;43    public SuiteWithParameters(Class<?> testClass) throws InitializationError {44        super(testClass); // TODO check this testClass45        this.testClass = testClass;46        try {47            rootPath = Paths.get(testClass.getResource("/").toURI());48        } catch (URISyntaxException e) {49            throw new InitializationError(e);50        }51    }52    @Override53    protected List<Suite> getChildren() {54        List<Suite> list = new LinkedList<Suite>();55        try {56            for(String dirname : getAnnotatedClasses(testClass)) {57                //getTestClass() // TODO check this out58                File directory = new File(rootPath.toFile(), dirname);59                for (File file : directory.listFiles()) {60                    if (file.isFile()) {61                        Path relPath = rootPath.relativize(Paths.get(file.getAbsolutePath()));62                        list.add(new ParameterizedFromFile(FibonacciTest.class, relPath.toFile()));63                    }64                    else65                        list.add(new ParameterizedFromFile(testClass, file));66                }67            }68        } catch (InitializationError initializationError) {69            initializationError.printStackTrace();70        } catch (Throwable throwable) {71            throwable.printStackTrace();72        }73        return list; // Collections.unmodifiableList(list);74    }75    @Override76    protected Description describeChild(Suite parameterized) {77        System.out.println(((ParameterizedFromFile) parameterized).fFile.toString());78        return parameterized.getDescription();79    }80    @Override81    protected void runChild(Suite suite, RunNotifier notifier) {82        suite.run(notifier);83    }84    private static String[] getAnnotatedClasses(Class<?> klass) throws InitializationError {85        SuiteWithParameters.SuiteDirectories annotation = klass.getAnnotation(SuiteWithParameters.SuiteDirectories.class);86        if(annotation == null) {87            throw new InitializationError(String.format("class \'%s\' must have a SuiteDirectories annotation", new Object[]{klass.getName()}));88        } else {89            return annotation.value();90        }91    }92    private static final List<Runner> NO_RUNNERS = Collections.emptyList();93    static class ParameterizedFromFile extends /*Parameterized*/ Suite {94        private final File fFile;95        private static final ParametersRunnerFactory DEFAULT_FACTORY = new BlockJUnit4ClassRunnerWithParametersFactory();96        private static final List<Runner> NO_RUNNERS = Collections.emptyList();97        private final List<Runner> runners;98        public ParameterizedFromFile(Class<?> klass, File file) throws Throwable {99            super(klass, NO_RUNNERS);100            fFile = file;101            ParametersRunnerFactory runnerFactory = this.getParametersRunnerFactory(klass);102            Parameterized.Parameters parameters = (Parameterized.Parameters)this.getParametersMethod().getAnnotation(Parameterized.Parameters.class);103            this.runners = Collections.unmodifiableList(this.createRunnersForParameters(this.allParameters(), parameters.name(), runnerFactory));104        }105        private ParametersRunnerFactory getParametersRunnerFactory(Class<?> klass) throws InstantiationException, IllegalAccessException {106            Parameterized.UseParametersRunnerFactory annotation = (Parameterized.UseParametersRunnerFactory)klass.getAnnotation(Parameterized.UseParametersRunnerFactory.class);107            if(annotation == null) {108                return DEFAULT_FACTORY;109            } else {110                Class factoryClass = annotation.value();111                return (ParametersRunnerFactory)factoryClass.newInstance();112            }113        }114        protected List<Runner> getChildren() {115            return this.runners;116        }117        private TestWithParameters createTestWithNotNormalizedParameters(String pattern, int index, Object parametersOrSingleParameter) {118            Object[] parameters = parametersOrSingleParameter instanceof Object[]?(Object[])((Object[])parametersOrSingleParameter):new Object[]{parametersOrSingleParameter};119            return createTestWithParameters(this.getTestClass(), pattern, index, parameters);120        }121        private Iterable<Object> allParameters() throws Throwable {122//            Object parameters = this.getParametersMethod().invokeExplosively((Object)null, new Object[0]);123//            if(parameters instanceof Iterable) {124//                return (Iterable)parameters;125//            } else if(parameters instanceof Object[]) {126//                return Arrays.asList((Object[]) ((Object[]) parameters));127//            } else {128//                throw this.parametersMethodReturnedWrongType();129//            }130            List<Object> list = new LinkedList<Object>();131            String resourceName = "/" + fFile.toString();132            InputStream stream = getTestClass().getJavaClass().getClass().getResourceAsStream(resourceName);133            Scanner sc = new Scanner(stream);134            while(sc.hasNext()) {135                list.add(sc.nextLine());136            }137            return list;138        }139        private FrameworkMethod getParametersMethod() throws Exception {140            List methods = this.getTestClass().getAnnotatedMethods(Parameterized.Parameters.class);141            Iterator i$ = methods.iterator();142            FrameworkMethod each;143            do {144                if(!i$.hasNext()) {145                    throw new Exception("No public static parameters method on class " + this.getTestClass().getName());146                }147                each = (FrameworkMethod)i$.next();148            } while(!each.isStatic() || !each.isPublic());149            return each;150        }151        private List<Runner> createRunnersForParameters(Iterable<Object> allParameters, String namePattern, ParametersRunnerFactory runnerFactory) throws InitializationError, Exception {152            try {153                List e = this.createTestsForParameters(allParameters, namePattern);154                ArrayList runners = new ArrayList();155                Iterator i$ = e.iterator();156                while(i$.hasNext()) {157                    TestWithParameters test = (TestWithParameters)i$.next();158                    runners.add(runnerFactory.createRunnerForTestWithParameters(test));159                }160                return runners;161            } catch (ClassCastException var8) {162                throw this.parametersMethodReturnedWrongType();163            }164        }165        private List<TestWithParameters> createTestsForParameters(Iterable<Object> allParameters, String namePattern) throws Exception {166            int i = 0;167            ArrayList children = new ArrayList();168            Iterator i$ = allParameters.iterator();169            while(i$.hasNext()) {170                Object parametersOfSingleTest = i$.next();171                children.add(this.createTestWithNotNormalizedParameters(namePattern, i++, parametersOfSingleTest));172            }173            return children;174        }175        private Exception parametersMethodReturnedWrongType() throws Exception {176            String className = this.getTestClass().getName();177            String methodName = this.getParametersMethod().getName();178            String message = MessageFormat.format("{0}.{1}() must return an Iterable of arrays.", new Object[]{className, methodName});179            return new Exception(message);180        }181        private static TestWithParameters createTestWithParameters(TestClass testClass, String pattern, int index, Object[] parameters) {182            String finalPattern = pattern.replaceAll("\\{index\\}", Integer.toString(index));183            String name = MessageFormat.format(finalPattern, parameters);184            return new TestWithParameters("[" + name + "]", testClass, Arrays.asList(parameters));185        }186    }187    @Retention(RetentionPolicy.RUNTIME)188    @Target({ElementType.TYPE})189    @Inherited190    public @interface SuiteDirectories {191        String[] value();192    }193}...Source:Parameterized.java  
1package org.junit.runners;23import java.text.MessageFormat;4import java.util.ArrayList;5import java.util.Arrays;6import java.util.Collections;7import java.util.Iterator;8import java.util.List;9import org.junit.runner.Runner;10import org.junit.runners.model.FrameworkMethod;11import org.junit.runners.model.TestClass;12import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory;13import org.junit.runners.parameterized.ParametersRunnerFactory;14import org.junit.runners.parameterized.TestWithParameters;1516public class Parameterized17  extends Suite18{19  private static final ParametersRunnerFactory DEFAULT_FACTORY = new BlockJUnit4ClassRunnerWithParametersFactory();20  private static final List<Runner> NO_RUNNERS = Collections.emptyList();21  private final List<Runner> runners;22  23  public Parameterized(Class<?> paramClass)24  {25    super(paramClass, NO_RUNNERS);26    paramClass = getParametersRunnerFactory(paramClass);27    Parameterized.Parameters localParameters = (Parameterized.Parameters)getParametersMethod().getAnnotation(Parameterized.Parameters.class);28    this.runners = Collections.unmodifiableList(createRunnersForParameters(allParameters(), localParameters.name(), paramClass));29  }30  31  private Iterable<Object> allParameters()32  {33    Object localObject = getParametersMethod().invokeExplosively(null, new Object[0]);34    if ((localObject instanceof Iterable)) {35      return (Iterable)localObject;36    }37    if ((localObject instanceof Object[])) {38      return Arrays.asList((Object[])localObject);39    }40    throw parametersMethodReturnedWrongType();41  }42  43  private List<Runner> createRunnersForParameters(Iterable<Object> paramIterable, String paramString, ParametersRunnerFactory paramParametersRunnerFactory)44  {45    try46    {47      paramString = createTestsForParameters(paramIterable, paramString);48      paramIterable = new ArrayList();49      paramString = paramString.iterator();50      while (paramString.hasNext()) {51        paramIterable.add(paramParametersRunnerFactory.createRunnerForTestWithParameters((TestWithParameters)paramString.next()));52      }53      return paramIterable;54    }55    catch (ClassCastException paramIterable)56    {57      label58:58      break label58;59    }60    paramIterable = parametersMethodReturnedWrongType();61    for (;;)62    {63      throw paramIterable;64    }65  }66  67  private TestWithParameters createTestWithNotNormalizedParameters(String paramString, int paramInt, Object paramObject)68  {69    if ((paramObject instanceof Object[])) {70      paramObject = (Object[])paramObject;71    } else {72      paramObject = new Object[] { paramObject };73    }74    return createTestWithParameters(getTestClass(), paramString, paramInt, paramObject);75  }76  77  private static TestWithParameters createTestWithParameters(TestClass paramTestClass, String paramString, int paramInt, Object[] paramArrayOfObject)78  {79    paramString = MessageFormat.format(paramString.replaceAll("\\{index\\}", Integer.toString(paramInt)), paramArrayOfObject);80    StringBuilder localStringBuilder = new StringBuilder();81    localStringBuilder.append("[");82    localStringBuilder.append(paramString);83    localStringBuilder.append("]");84    return new TestWithParameters(localStringBuilder.toString(), paramTestClass, Arrays.asList(paramArrayOfObject));85  }86  87  private List<TestWithParameters> createTestsForParameters(Iterable<Object> paramIterable, String paramString)88  {89    ArrayList localArrayList = new ArrayList();90    paramIterable = paramIterable.iterator();91    int i = 0;92    while (paramIterable.hasNext())93    {94      localArrayList.add(createTestWithNotNormalizedParameters(paramString, i, paramIterable.next()));95      i += 1;96    }97    return localArrayList;98  }99  100  private FrameworkMethod getParametersMethod()101  {102    Object localObject = getTestClass().getAnnotatedMethods(Parameterized.Parameters.class).iterator();103    while (((Iterator)localObject).hasNext())104    {105      FrameworkMethod localFrameworkMethod = (FrameworkMethod)((Iterator)localObject).next();106      if ((localFrameworkMethod.isStatic()) && (localFrameworkMethod.isPublic())) {107        return localFrameworkMethod;108      }109    }110    localObject = new StringBuilder();111    ((StringBuilder)localObject).append("No public static parameters method on class ");112    ((StringBuilder)localObject).append(getTestClass().getName());113    localObject = new Exception(((StringBuilder)localObject).toString());114    for (;;)115    {116      throw ((Throwable)localObject);117    }118  }119  120  private ParametersRunnerFactory getParametersRunnerFactory(Class<?> paramClass)121  {122    paramClass = (Parameterized.UseParametersRunnerFactory)paramClass.getAnnotation(Parameterized.UseParametersRunnerFactory.class);123    if (paramClass == null) {124      return DEFAULT_FACTORY;125    }126    return (ParametersRunnerFactory)paramClass.value().newInstance();127  }128  129  private Exception parametersMethodReturnedWrongType()130  {131    return new Exception(MessageFormat.format("{0}.{1}() must return an Iterable of arrays.", new Object[] { getTestClass().getName(), getParametersMethod().getName() }));132  }133  134  protected List<Runner> getChildren()135  {136    return this.runners;137  }138}139140
141/* Location:           L:\local\mybackup\temp\qq_apk\com.tencent.mobileqq\classes16.jar
142 * Qualified Name:     org.junit.runners.Parameterized
143 * JD-Core Version:    0.7.0.1
...Source:EnsureCorrectRunsWithProcessor.java  
1/*2 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license3 * agreements. See the NOTICE file distributed with this work for additional information regarding4 * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the5 * "License"); you may not use this file except in compliance with the License. You may obtain a6 * 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, software distributed under the License11 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express12 * or implied. See the License for the specific language governing permissions and limitations under13 * the License.14 */15package org.apache.geode.javac;16import java.util.Set;17import javax.annotation.processing.AbstractProcessor;18import javax.annotation.processing.Messager;19import javax.annotation.processing.ProcessingEnvironment;20import javax.annotation.processing.RoundEnvironment;21import javax.annotation.processing.SupportedAnnotationTypes;22import javax.annotation.processing.SupportedSourceVersion;23import javax.lang.model.SourceVersion;24import javax.lang.model.element.AnnotationMirror;25import javax.lang.model.element.Element;26import javax.lang.model.element.ElementKind;27import javax.lang.model.element.TypeElement;28import javax.lang.model.type.DeclaredType;29import javax.lang.model.type.MirroredTypeException;30import javax.tools.Diagnostic;31import org.junit.runner.RunWith;32import org.junit.runners.Parameterized;33@SupportedAnnotationTypes("org.junit.runner.RunWith")34@SupportedSourceVersion(SourceVersion.RELEASE_8)35public class EnsureCorrectRunsWithProcessor extends AbstractProcessor {36  private static final String FACTORY_CANONICAL_NAME = "org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactory";37  private static final String FACTORY_SIMPLE_NAME = "CategoryWithParameterizedRunnerFactory";38  private static final String RUNWITH = RunWith.class.getCanonicalName();39  private Messager messager;40  @Override41  public synchronized void init(ProcessingEnvironment env) {42    super.init(env);43    messager = env.getMessager();44  }45  @Override46  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {47    boolean hasErrors = false;48    for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(RunWith.class)) {49      if (annotatedElement.getKind() != ElementKind.CLASS) {50        continue;51      }52      TypeElement typeElement = (TypeElement) annotatedElement;53      boolean hasUseParameterizedRunnerFactory = false;54      boolean hasRunWithParameterized = false;55      for (AnnotationMirror am : typeElement.getAnnotationMirrors()) {56        String clazz = am.getAnnotationType().toString();57        if (clazz.equals(RunWith.class.getCanonicalName())) {58          hasRunWithParameterized = isRunWithParameterized(typeElement);59        }60        if (clazz.equals(Parameterized.UseParametersRunnerFactory.class.getCanonicalName())) {61          hasUseParameterizedRunnerFactory = isUseParameterizedRunnerFactory(typeElement);62        }63      }64      if (hasRunWithParameterized && !hasUseParameterizedRunnerFactory) {65        error(typeElement, "class is annotated with @RunWith(Parameterized.class) but is missing the annotation @Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class)");66        hasErrors = true;67      }68    }69    return hasErrors;70  }71  private boolean isRunWithParameterized(TypeElement typeElement) {72    RunWith runWith = typeElement.getAnnotation(RunWith.class);73    String runWithValue;74    try {75      runWithValue = runWith.value().getSimpleName();76    } catch (MirroredTypeException mex) {77      DeclaredType classTypeMirror = (DeclaredType) mex.getTypeMirror();78      TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();79      runWithValue = classTypeElement.getSimpleName().toString();80    }81    if (runWithValue == null) {82      return false;83    }84    return runWithValue.equals(Parameterized.class.getCanonicalName())85        || runWithValue.equals(Parameterized.class.getSimpleName());86  }87  private boolean isUseParameterizedRunnerFactory(TypeElement typeElement) {88    Parameterized.UseParametersRunnerFactory89        runnerFactory = typeElement.getAnnotation(Parameterized.UseParametersRunnerFactory.class);90    String runnerFactoryValue;91    try {92      runnerFactoryValue = runnerFactory.value().getSimpleName();93    } catch (MirroredTypeException mex) {94      DeclaredType classTypeMirror = (DeclaredType) mex.getTypeMirror();95      TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();96      runnerFactoryValue = classTypeElement.getSimpleName().toString();97    }98    if (runnerFactoryValue == null) {99      return false;100    }101    return runnerFactoryValue.equals(FACTORY_CANONICAL_NAME)102        || runnerFactoryValue.equals(FACTORY_SIMPLE_NAME);103  }104  private void error(Element e, String msg, Object... args) {105    messager.printMessage(106        Diagnostic.Kind.ERROR,107        String.format(msg, args),108        e);109  }110}...Source:SemaphoreQuorumReadTest.java  
1/*2 * Copyright (c) 2008-2019, 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.quorum.semaphore;17import com.hazelcast.config.Config;18import com.hazelcast.core.ISemaphore;19import com.hazelcast.quorum.AbstractQuorumTest;20import com.hazelcast.quorum.QuorumException;21import com.hazelcast.quorum.QuorumType;22import com.hazelcast.test.HazelcastSerialParametersRunnerFactory;23import com.hazelcast.test.TestHazelcastInstanceFactory;24import com.hazelcast.test.annotation.ParallelTest;25import com.hazelcast.test.annotation.QuickTest;26import org.junit.AfterClass;27import org.junit.BeforeClass;28import org.junit.Test;29import org.junit.experimental.categories.Category;30import org.junit.runner.RunWith;31import org.junit.runners.Parameterized;32import org.junit.runners.Parameterized.Parameter;33import org.junit.runners.Parameterized.Parameters;34import org.junit.runners.Parameterized.UseParametersRunnerFactory;35import static java.util.Arrays.asList;36@RunWith(Parameterized.class)37@UseParametersRunnerFactory(HazelcastSerialParametersRunnerFactory.class)38@Category({QuickTest.class, ParallelTest.class})39public class SemaphoreQuorumReadTest extends AbstractQuorumTest {40    @Parameters(name = "classLoaderType:{0}")41    public static Iterable<Object[]> parameters() {42        return asList(new Object[][]{{QuorumType.READ}, {QuorumType.READ_WRITE}});43    }44    @Parameter45    public static QuorumType quorumType;46    @BeforeClass47    public static void setUp() {48        initTestEnvironment(new Config(), new TestHazelcastInstanceFactory());49    }50    @AfterClass51    public static void tearDown() {52        shutdownTestEnvironment();53    }54    @Test55    public void availablePermits_successful_whenQuorumSize_met() {56        semaphore(0).availablePermits();57    }58    @Test(expected = QuorumException.class)59    public void availablePermits_successful_whenQuorumSize_notMet() {60        semaphore(3).availablePermits();61    }62    protected ISemaphore semaphore(int index) {63        return semaphore(index, quorumType);64    }65}...Source:ParameterizedClassRule.java  
1/*2 * Copyright (C) 2015-2017 NS Solutions Corporation3 *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.htmlhifive.pitalium.junit;17import java.lang.annotation.ElementType;18import java.lang.annotation.Retention;19import java.lang.annotation.RetentionPolicy;20import java.lang.annotation.Target;21/**22 * <p>23 * {@link org.junit.runners.Parameterized}ãã¹ãã«ããã¦ãåãã©ã¡ã¼ã¿ã¼æ¯ã«å
¨ã¦ã®ã¡ã½ããå§ã¾ãåã¨å¾ãããã¯åºæ¥ãã¡ã½ããã¾ãã¯ãã£ã¼ã«ããæå®ãã¾ãã24 * </p>25 * 以ä¸ã®ãµã³ãã«ã®ããã«å©ç¨ãã¦ãã ããã26 * 27 * <pre>28 * @RunWith(Parameterized.class)29 * @Parameterized.UseParametersRunnerFactory(PtlBlockJUnit4ClassRunnerWithParametersFactory.class)30 * public class SampleTest {31 * 32 *     @Parameterized.Parameters33 *     public static Collection<Object[]> parameters() {34 *         return Arrays.asList(new Object[] { "1", 1 }, new Object[] { "2", 2 });35 *     }36 * 37 *     @ParameterizedClassRule38 *     public static ParameterizedTestWatcher parameterizedWatcher = new ParameterizedTestWatcher() {39 *     }40 * 41 * }42 * </pre>43 * 44 * @see org.junit.ClassRule45 * @see ParameterizedTestRule46 * @author nakatani47 */48@Retention(RetentionPolicy.RUNTIME)49@Target({ ElementType.FIELD, ElementType.METHOD })50public @interface ParameterizedClassRule {51}...Source:ParameterizedBeforeClass.java  
1/*2 * Copyright (C) 2015-2017 NS Solutions Corporation3 *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.htmlhifive.pitalium.junit;17import java.lang.annotation.ElementType;18import java.lang.annotation.Retention;19import java.lang.annotation.RetentionPolicy;20import java.lang.annotation.Target;21/**22 * <p>23 * {@link org.junit.runners.Parameterized}ãã¹ãã«ããã¦ãåãã©ã¡ã¼ã¿ã¼æ¯ã«å
¨ã¦ã®ã¡ã½ãããå§ã¾ãåã«ä¸åº¦ã ãå¼ã°ããã¡ã½ãããæå®ãã¾ãã24 * </p>25 * 以ä¸ã®ãµã³ãã«ã®ããã«å©ç¨ãã¦ãã ããã26 * 27 * <pre>28 * @RunWith(Parameterized.class)29 * @Parameterized.UseParametersRunnerFactory(PtlBlockJUnit4ClassRunnerWithParametersFactory.class)30 * public class SampleTest {31 * 32 *     @Parameterized.Parameters33 *     public static Collection<Object[]> parameters() {34 *         return Arrays.asList(new Object[] {"1", 1}, new Object[] {"2", 2});35 *     }36 * 37 *     @ParameterizedBeforeClass38 *     public static void parameterizedBeforeClass(<b>String param1, int param2</b>) {39 * 40 *     }41 * 42 * }43 * </pre>44 * 45 * @see ParameterizedBeforeClass46 * @author nakatani47 */48@Retention(RetentionPolicy.RUNTIME)49@Target(ElementType.METHOD)50public @interface ParameterizedBeforeClass {51}...Source:ParameterizedAfterClass.java  
1/*2 * Copyright (C) 2015-2017 NS Solutions Corporation3 *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.htmlhifive.pitalium.junit;17import java.lang.annotation.ElementType;18import java.lang.annotation.Retention;19import java.lang.annotation.RetentionPolicy;20import java.lang.annotation.Target;21/**22 * <p>23 * {@link org.junit.runners.Parameterized}ãã¹ãã«ããã¦ãåãã©ã¡ã¼ã¿ã¼æ¯ã«å
¨ã¦ã®ã¡ã½ãããçµãã£ãæã«ä¸åº¦ã ãå¼ã°ããã¡ã½ãããæå®ãã¾ãã24 * </p>25 * 以ä¸ã®ãµã³ãã«ã®ããã«å©ç¨ãã¦ãã ããã26 * 27 * <pre>28 * @RunWith(Parameterized.class)29 * @Parameterized.UseParametersRunnerFactory(PtlBlockJUnit4ClassRunnerWithParametersFactory.class)30 * public class SampleTest {31 * 32 *     @Parameterized.Parameters33 *     public static Collection<Object[]> parameters() {34 *         return Arrays.asList(new Object[] {"1", 1}, new Object[] {"2", 2});35 *     }36 * 37 *     @ParameterizedAfterClass38 *     public static void parameterizedAfterClass(<b>String param1, int param2</b>) {39 * 40 *     }41 * 42 * }43 * </pre>44 * 45 * @see org.junit.AfterClass46 * @author nakatani47 */48@Retention(RetentionPolicy.RUNTIME)49@Target(ElementType.METHOD)50public @interface ParameterizedAfterClass {51}...Source:Parameterized$UseParametersRunnerFactory.java  
1package org.junit.runners;23import java.lang.annotation.Annotation;4import java.lang.annotation.Inherited;5import java.lang.annotation.Retention;6import java.lang.annotation.RetentionPolicy;7import java.lang.annotation.Target;8import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory;9import org.junit.runners.parameterized.ParametersRunnerFactory;1011@Inherited12@Retention(RetentionPolicy.RUNTIME)13@Target({java.lang.annotation.ElementType.TYPE})14public @interface Parameterized$UseParametersRunnerFactory15{16  Class<? extends ParametersRunnerFactory> value() default BlockJUnit4ClassRunnerWithParametersFactory.class;17}1819
20/* Location:           L:\local\mybackup\temp\qq_apk\com.tencent.mobileqq\classes16.jar
21 * Qualified Name:     org.junit.runners.Parameterized.UseParametersRunnerFactory
22 * JD-Core Version:    0.7.0.1
...Annotation Type Parameterized.UseParametersRunnerFactory
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 a;10    private int b;11    private int c;12    public ParameterizedTest(int a, int b, int c) {13        this.a = a;14        this.b = b;15        this.c = c;16    }17    public static Collection<Object[]> getData(){18        return Arrays.asList(new Object[][]{19                {1, 2, 3},20                {2, 3, 5},21                {3, 4, 7},22                {4, 5, 9},23                {5, 6, 11}24        });25    }26    public void testAdd(){27        System.out.println(a + "+" + b + "=" + c);28    }29}30import org.junit.Test;31import org.junit.runner.RunWith;32import org.junit.runners.Parameterized;33import java.util.Arrays;34import java.util.Collection;35@RunWith(Parameterized.class)36public class ParameterizedTest {37    private int a;38    private int b;39    private int c;40    public ParameterizedTest(int a, int b, int c) {41        this.a = a;42        this.b = b;43        this.c = c;44    }45    public static Collection<Object[]> getData(){46        return DataProvider.getData();47    }48    public void testAdd(){49        System.out.println(a + "+" + b + "=" + c);50    }51}52class DataProvider {53    public static Collection<Object[]> getData(){54        return Arrays.asList(new Object[][]{55                {1, 2, 3},56                {2, 3, 5},57                {3, 4, 7},58                {4, 5, 9},59                {5, 6,Annotation Type Parameterized.UseParametersRunnerFactory
Using AI Code Generation
1import org.junit.runner.RunWith;2import org.junit.runners.Parameterized.UseParametersRunnerFactory;3import org.junit.runners.Parameterized.Parameters;4import org.junit.runners.Parameterized;5import org.junit.runners.Parameterized.Parameter;6import org.junit.Test;7import static org.junit.Assert.assertEquals;8@RunWith(Parameterized.class)9@UseParametersRunnerFactory(Parameterized.UseParametersRunnerFactory.class)10public class ParameterizedTest {11    @Parameter(0)12    public int m1;13    @Parameter(1)14    public int m2;15    @Parameter(2)16    public int result;17    public static Object[][] data() {18        return new Object[][] { { 1, 1, 2 }, { 5, 2, 7 }, { 121, 4, 125 } };19    }20    public void testAdd() {21        assertEquals(result, new MyClass().add(m1, m2));22    }23}24import org.junit.runner.RunWith;25import org.junit.runners.Parameterized.UseParametersRunnerFactory;26import org.junit.runners.Parameterized.Parameters;27import org.junit.runners.Parameterized;28import org.junit.runners.Parameterized.Parameter;29import org.junit.Test;30import static org.junit.Assert.assertEquals;31@RunWith(Parameterized.class)32@UseParametersRunnerFactory(Parameterized.UseParametersRunnerFactory.class)33public class ParameterizedTest {34    @Parameter(0)35    public int m1;36    @Parameter(1)37    public int m2;38    @Parameter(2)39    public int result;40    public static Object[][] data() {41        return new Object[][] { { 1, 1, 2 }, { 5, 2, 7 }, { 121, 4, 125 } };42    }43    public void testAdd() {44        assertEquals(result, new MyClass().add(m1, m2));45    }46}47import org.junit.runner.RunWith;48import org.junit.runners.Parameterized.UseParametersRunnerFactory;49import org.junit.runners.Parameterized.Parameters;50import org.junit.runners.Parameterized;51import org.junit.runners.Parameterized.Parameter;52import org.junit.Test;53import static org.junit.AssertAnnotation Type Parameterized.UseParametersRunnerFactory
Using AI Code Generation
1public class ParameterizedTest {2    public static Collection<Object[]> data() {3        return Arrays.asList(new Object[][] {4                 { 0, 0 }, { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 }, { 5, 5 }5           });6    }7    private int fInput;8    private int fExpected;9    public ParameterizedTest(int input, int expected) {10        fInput= input;11        fExpected= expected;12    }13    public void test() {14        assertEquals(fExpected, fInput);15    }16}17@RunWith(JUnitParamsRunner.class)18public class ParameterizedTest {19    private int fInput;20    private int fExpected;21    public ParameterizedTest(int input, int expected) {22        fInput= input;23        fExpected= expected;24    }25    @Parameters(method = "parametersToTestWith")26    public void test(int input, int expected) {27        assertEquals(expected, input);28    }29    private static Object[] parametersToTestWith() {30        return $(31                $(0, 0),32                $(1, 1),33                $(2, 2),34                $(3, 3),35                $(4, 4),36                $(5, 5)37        );38    }39}40@RunWith(JUnitParamsRunner.class)41public class ParameterizedTest {42    public void test(int input, int expected) {43        assertEquals(expected, input);44    }45    private static Object[] parametersForTest() {46        return $(47                $(0, 0),48                $(1, 1),49                $(2, 2),50                $(3, 3),51                $(4, 4),52                $(5, 5)53        );54    }55}56@RunWith(JUnitParamsRunner.class)57public class ParameterizedTest {58    public void test(int input, int expected) {59        assertEquals(expected, input);60    }61    private static Object[] parametersForTest() {62        return new Object[] {63                new Object[] { 0, 0 },64                new Object[] { 1,Annotation Type Parameterized.UseParametersRunnerFactory
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestClass {3    private int num1;4    private int num2;5    private int expected;6    public TestClass(int num1, int num2, int expected) {7        this.num1 = num1;8        this.num2 = num2;9        this.expected = expected;10    }11    public static Collection<Object[]> data() {12        return Arrays.asList(new Object[][]{13                {1, 1, 2},14                {2, 2, 4},15                {3, 3, 6},16                {4, 4, 8},17                {5, 5, 10},18                {6, 6, 12},19                {7, 7, 14},20                {8, 8, 16},21                {9, 9, 18},22                {10, 10, 20},23        });24    }25    public void test() {26        assertEquals(expected, num1 + num2);27    }28}29@RunWith(Parameterized.class)30public class TestClass {31    private int num1;32    private int num2;33    private int expected;34    public TestClass(int num1, int num2, int expected) {35        this.num1 = num1;36        this.num2 = num2;37        this.expected = expected;38    }39    public static Collection<Object[]> data() {40        return Arrays.asList(new Object[][]{41                {1, 1, 2Annotation Type Parameterized.UseParametersRunnerFactory
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestParameters {3    public static Collection<Object[]> data() {4        return Arrays.asList(new Object[][] {     5                 { 1, 2 }, { 3, 4 }, { 5, 6 }  6           });7    }8    private int fInput;9    private int fExpected;10    public TestParameters(int input, int expected) {11        fInput= input;12        fExpected= expected;13    }14    public void test() {15        assertEquals(fExpected, fInput);16    }17}18test(TestParameters)  Time elapsed: 0.001 sec  <<< ERROR!19test(TestParameters)  Time elapsed: 0 sec  <<< ERROR!20test(TestParameters)  Time elapsed: 0 sec  <<< ERROR!21package com.journaldev.junit.parameters;22import static org.junit.Assert.assertEquals;23import java.util.Arrays;24import java.util.Collection;25import org.junit.Test;26import org.junit.runner.RunWith;27import org.junit.runners.Parameterized;28import org.junit.runners.Parameterized.Parameters;29@RunWith(Parameterized.class)30public class ParameterizedTest {31    private int numberA;32    private int numberB;33    private int expectedSum;34    public ParameterizedTest(int numberA, int numberB, int expectedSum) {35        this.numberA = numberA;36        this.numberB = numberB;37        this.expectedSum = expectedSum;38    }39    public static Collection<Object[]> data() {40        Object[][] data = new Object[][] { { 1, 2,Annotation Type Parameterized.UseParametersRunnerFactory
Using AI Code Generation
1@UseParametersRunnerFactory(Parameterized.UseParametersRunnerFactory.class)2public class ParameterizedTest {3    public static Collection<Object[]> data() {4        return Arrays.asList(new Object[][]{5                {0, false},6                {1, true},7                {2, true},8                {3, false},9                {4, true},10                {5, false},11                {6, false},12                {7, false},13                {8, true},14                {9, false},15                {10, true}});16    }17    public int input;18    @Parameter(1)19    public boolean expected;20    public void test() {21        System.out.println(input + " is prime number? " + expected);22        assertEquals(expected, isPrimeNumber(input));23    }24    private boolean isPrimeNumber(int num) {25        for (int i = 2; i <= num / 2; i++) {26            if (num % i == 0) {27                return false;28            }29        }30        return true;31    }32}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!!
