Best junit code snippet using org.junit.runners.Parameterized
...3import java.lang.reflect.Field;4import java.util.List;5import org.junit.runner.notification.RunNotifier;6import org.junit.runners.BlockJUnit4ClassRunner;7import org.junit.runners.Parameterized;8import org.junit.runners.model.FrameworkField;9import org.junit.runners.model.FrameworkMethod;10import org.junit.runners.model.InitializationError;11import org.junit.runners.model.Statement;12public class BlockJUnit4ClassRunnerWithParameters extends BlockJUnit4ClassRunner {13 private final String name;14 private final Object[] parameters;15 public BlockJUnit4ClassRunnerWithParameters(TestWithParameters test) throws InitializationError {16 super(test.getTestClass().getJavaClass());17 this.parameters = test.getParameters().toArray(new Object[test.getParameters().size()]);18 this.name = test.getName();19 }20 @Override // org.junit.runners.BlockJUnit4ClassRunner21 public Object createTest() throws Exception {22 if (fieldsAreAnnotated()) {23 return createTestUsingFieldInjection();24 }25 return createTestUsingConstructorInjection();26 }27 private Object createTestUsingConstructorInjection() throws Exception {28 return getTestClass().getOnlyConstructor().newInstance(this.parameters);29 }30 private Object createTestUsingFieldInjection() throws Exception {31 List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();32 if (annotatedFieldsByParameter.size() == this.parameters.length) {33 Object testClassInstance = getTestClass().getJavaClass().newInstance();34 for (FrameworkField each : annotatedFieldsByParameter) {35 Field field = each.getField();36 int index = ((Parameterized.Parameter) field.getAnnotation(Parameterized.Parameter.class)).value();37 try {38 field.set(testClassInstance, this.parameters[index]);39 } catch (IllegalArgumentException iare) {40 throw new Exception(getTestClass().getName() + ": Trying to set " + field.getName() + " with the value " + this.parameters[index] + " that is not the right type (" + this.parameters[index].getClass().getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare);41 }42 }43 return testClassInstance;44 }45 throw new Exception("Wrong number of parameters and @Parameter fields. @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + this.parameters.length + ".");46 }47 /* access modifiers changed from: protected */48 @Override // org.junit.runners.ParentRunner49 public String getName() {50 return this.name;51 }52 /* access modifiers changed from: protected */53 @Override // org.junit.runners.BlockJUnit4ClassRunner54 public String testName(FrameworkMethod method) {55 return method.getName() + getName();56 }57 /* access modifiers changed from: protected */58 @Override // org.junit.runners.BlockJUnit4ClassRunner59 public void validateConstructor(List<Throwable> errors) {60 validateOnlyOneConstructor(errors);61 if (fieldsAreAnnotated()) {62 validateZeroArgConstructor(errors);63 }64 }65 /* access modifiers changed from: protected */66 @Override // org.junit.runners.BlockJUnit4ClassRunner67 public void validateFields(List<Throwable> errors) {68 super.validateFields(errors);69 if (fieldsAreAnnotated()) {70 List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();71 int[] usedIndices = new int[annotatedFieldsByParameter.size()];72 for (FrameworkField each : annotatedFieldsByParameter) {73 int index = ((Parameterized.Parameter) each.getField().getAnnotation(Parameterized.Parameter.class)).value();74 if (index < 0 || index > annotatedFieldsByParameter.size() - 1) {75 errors.add(new Exception("Invalid @Parameter value: " + index + ". @Parameter fields counted: " + annotatedFieldsByParameter.size() + ". Please use an index between 0 and " + (annotatedFieldsByParameter.size() - 1) + "."));76 } else {77 usedIndices[index] = usedIndices[index] + 1;78 }79 }80 for (int index2 = 0; index2 < usedIndices.length; index2++) {81 int numberOfUse = usedIndices[index2];82 if (numberOfUse == 0) {83 errors.add(new Exception("@Parameter(" + index2 + ") is never used."));84 } else if (numberOfUse > 1) {85 errors.add(new Exception("@Parameter(" + index2 + ") is used more than once (" + numberOfUse + ")."));86 }87 }88 }89 }90 /* access modifiers changed from: protected */91 @Override // org.junit.runners.ParentRunner92 public Statement classBlock(RunNotifier notifier) {93 return childrenInvoker(notifier);94 }95 /* access modifiers changed from: protected */96 @Override // org.junit.runners.ParentRunner97 public Annotation[] getRunnerAnnotations() {98 return new Annotation[0];99 }100 private List<FrameworkField> getAnnotatedFieldsByParameter() {101 return getTestClass().getAnnotatedFields(Parameterized.Parameter.class);102 }103 private boolean fieldsAreAnnotated() {104 return !getAnnotatedFieldsByParameter().isEmpty();105 }106}...
...15 */16package com.hazelcast.test;17import org.junit.runner.notification.RunNotifier;18import org.junit.runners.BlockJUnit4ClassRunner;19import org.junit.runners.Parameterized;20import org.junit.runners.model.FrameworkField;21import org.junit.runners.model.FrameworkMethod;22import org.junit.runners.model.InitializationError;23import org.junit.runners.model.Statement;24import java.lang.annotation.Annotation;25import java.lang.reflect.Field;26import java.util.List;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 clazz}36 *37 * @throws org.junit.runners.model.InitializationError if the test class is malformed.38 */39 public AbstractParameterizedHazelcastClassRunner(Class<?> clazz) throws InitializationError {40 super(clazz);41 }42 public AbstractParameterizedHazelcastClassRunner(Class<?> clazz, Object[] parameters, String name)43 throws InitializationError {44 super(clazz);45 fParameters = parameters;46 fName = name;47 isParameterized = true;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 @Override83 protected void validateConstructor(List<Throwable> errors) {84 validateOnlyOneConstructor(errors);85 if (fieldsAreAnnotated()) {86 validateZeroArgConstructor(errors);87 }88 }89 private Object createTestUsingFieldInjection() throws Exception {90 List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();91 if (annotatedFieldsByParameter.size() != fParameters.length) {92 throw new Exception("Wrong number of parameters and @Parameter fields."93 + " @Parameter fields counted: " + annotatedFieldsByParameter.size()94 + ", available parameters: " + fParameters.length + ".");95 }96 Object testClassInstance = getTestClass().getJavaClass().newInstance();97 for (FrameworkField each : annotatedFieldsByParameter) {98 Field field = each.getField();99 Parameterized.Parameter annotation = field.getAnnotation(Parameterized.Parameter.class);100 int index = annotation.value();101 try {102 field.set(testClassInstance, fParameters[index]);103 } catch (IllegalArgumentException iare) {104 throw new Exception(getTestClass().getName() + ": Trying to set " + field.getName()105 + " with the value " + fParameters[index]106 + " that is not the right type (" + fParameters[index].getClass().getSimpleName() + " instead of "107 + field.getType().getSimpleName() + ").", iare);108 }109 }110 return testClassInstance;111 }112 private boolean fieldsAreAnnotated() {113 return !getAnnotatedFieldsByParameter().isEmpty();114 }115 private List<FrameworkField> getAnnotatedFieldsByParameter() {116 return getTestClass().getAnnotatedFields(Parameterized.Parameter.class);117 }118 @Override119 protected Statement classBlock(RunNotifier notifier) {120 if (isParameterized) {121 return childrenInvoker(notifier);122 } else {123 return super.classBlock(notifier);124 }125 }126 @Override127 protected Annotation[] getRunnerAnnotations() {128 return new Annotation[0];129 }130}...
...17import org.eclipse.papyrus.junit.framework.classification.rules.Conditional;18import org.junit.rules.TestRule;19import org.junit.runner.Description;20import org.junit.runner.notification.RunNotifier;21import org.junit.runners.Parameterized;22import org.junit.runners.Parameterized.Parameters;23import org.junit.runners.Parameterized.UseParametersRunnerFactory;24import org.junit.runners.model.FrameworkMethod;25import org.junit.runners.model.InitializationError;26import org.junit.runners.model.Statement;27import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;28import org.junit.runners.parameterized.TestWithParameters;29/**30 * A Test Runner which is aware of Classification-related annotations and {@link Conditional @Conditional} tests,31 * for use with test {@link Parameters}.32 *33 * It ignores the test methods according to their annotations, and the policy defined34 * in {@link ClassificationConfig}.35 *36 * @see Parameterized37 * @see UseParametersRunnerFactory38 * @see ClassificationRunnerWithParametersFactory39 * @see ClassificationConfig40 * @see TestCategory41 * @see Conditional42 *43 */44public class ClassificationRunnerWithParameters extends BlockJUnit4ClassRunnerWithParameters {45 private final ClassificationRunnerImpl impl;46 public ClassificationRunnerWithParameters(TestWithParameters test) throws InitializationError {47 super(test);48 this.impl = new ClassificationRunnerImpl(new ClassificationRunnerImpl.Delegate() {49 @Override50 public void runChild(FrameworkMethod method, RunNotifier notifier) {...
...18import com.google.errorprone.CompilationTestHelper;19import org.junit.Test;20import org.junit.runner.RunWith;21import org.junit.runners.JUnit4;22/** Tests for {@link ParametersButNotParameterized}. */23@RunWith(JUnit4.class)24public final class ParametersButNotParameterizedTest {25 private final CompilationTestHelper helper =26 CompilationTestHelper.newInstance(ParametersButNotParameterized.class, getClass());27 private final BugCheckerRefactoringTestHelper refactoringHelper =28 BugCheckerRefactoringTestHelper.newInstance(ParametersButNotParameterized.class, getClass());29 @Test30 public void positive() {31 refactoringHelper32 .addInputLines(33 "Test.java",34 "import org.junit.runner.RunWith;",35 "import org.junit.runners.JUnit4;",36 "import org.junit.runners.Parameterized.Parameter;",37 "@RunWith(JUnit4.class)",38 "public class Test {",39 " @Parameter public int foo;",40 "}")41 .addOutputLines(42 "Test.java",43 "import org.junit.runner.RunWith;",44 "import org.junit.runners.JUnit4;",45 "import org.junit.runners.Parameterized;",46 "import org.junit.runners.Parameterized.Parameter;",47 "@RunWith(Parameterized.class)",48 "public class Test {",49 " @Parameter public int foo;",50 "}")51 .doTest();52 }53 @Test54 public void alreadyParameterized_noFinding() {55 helper56 .addSourceLines(57 "Test.java",58 "import org.junit.runner.RunWith;",59 "import org.junit.runners.Parameterized;",60 "import org.junit.runners.Parameterized.Parameter;",61 "@RunWith(Parameterized.class)",62 "public class Test {",63 " @Parameter public int foo;",64 "}")65 .doTest();66 }67 @Test68 public void noParameters_noFinding() {69 helper70 .addSourceLines(71 "Test.java",72 "import org.junit.runner.RunWith;",73 "import org.junit.runners.JUnit4;",74 "@RunWith(JUnit4.class)",75 "public class Test {",...
1package junit4.v4_12;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.junit.runner.Runner;5import org.junit.runners.Parameterized;6import org.junit.runners.Parameterized.Parameter;7import org.junit.runners.Parameterized.Parameters;8import org.junit.runners.Parameterized.UseParametersRunnerFactory;9import org.junit.runners.model.InitializationError;10import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;11import org.junit.runners.parameterized.ParametersRunnerFactory;12import org.junit.runners.parameterized.TestWithParameters;13import java.util.Arrays;14import java.util.List;15/**16 * {@link UseParametersRunnerFactory} ãç¡çç¢ç使ã£ã¦ã¿ãã17 *18 * @author irof19 */20@RunWith(Parameterized.class)21@UseParametersRunnerFactory(PracUseParametersRunnerFactory.FriendlyRunner.Factory.class)22public class PracUseParametersRunnerFactory {23 /**24 * ãã©ã¡ã¼ã¿ãä¸ã¤ã®æã¯åç´ãªãªã¹ãã® <code>@parameters</code> ã¨25 * åä¸ã® <code>@Parameter</code> ãã£ã¼ã«ãã§è¯ããªã£ãã26 */27 @Parameters28 public static List<String> data() {29 return Arrays.asList("A", "B", "C");30 }31 @Parameter32 public String arg;33 @Test34 public void test() throws Exception {...
...17import org.junit.runners.parameterized.ParametersRunnerFactory;18import org.junit.runners.parameterized.TestWithParameters;19/**20 * {@link ParametersRunnerFactory} for21 * {@link org.junit.runners.Parameterized.UseParametersRunnerFactory UseParametersRunnerFactory} annotation22 * to run tests with parameters in a separate ClassLoader.23 *24 * @see Isolated25 */26public class IsolatedParametersRunnerFactory implements ParametersRunnerFactory {27 @Override28 public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {29 return new IsolatedParameterizedRunner(test);30 }31 private static class IsolatedParameterizedRunner extends BlockJUnit4ClassRunnerWithParameters {32 public IsolatedParameterizedRunner(TestWithParameters test) throws InitializationError {33 super(isolated(test));34 }35 private static TestWithParameters isolated(TestWithParameters test) throws InitializationError {36 Class<?> testClass = test.getTestClass().getJavaClass();37 Class<?> isolatedTestClass = IsolatedClassLoader.isolatedTestClass(testClass);38 return new TestWithParameters(test.getName(), new TestClass(isolatedTestClass), test.getParameters());39 }40 }41}...
...14 *****************************************************************************/15package org.eclipse.papyrus.junit.framework.classification;16import org.junit.runner.RunWith;17import org.junit.runner.Runner;18import org.junit.runners.Parameterized;19import org.junit.runners.Parameterized.UseParametersRunnerFactory;20import org.junit.runners.model.InitializationError;21import org.junit.runners.parameterized.ParametersRunnerFactory;22import org.junit.runners.parameterized.TestWithParameters;23/**24 * Factory for classification-sensitive parameterized test suites.25 * Specify this factory in the {@literal @}{@link UseParametersRunnerFactory}26 * annotation on your <tt>{@literal @}{@link RunWith}({@link Parameterized}.class)</tt>27 * test class to support the classfication and condition annotations of the Papyrus28 * test framework.29 * 30 * @see Parameterized31 * @see UseParametersRunnerFactory32 * @since 1.233 */34public class ClassificationRunnerWithParametersFactory implements ParametersRunnerFactory {35 public ClassificationRunnerWithParametersFactory() {36 super();37 }38 @Override39 public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {40 return new ClassificationRunnerWithParameters(test);41 }42}...
Source: AllRunnersTests.java
2import org.junit.runner.RunWith;3import org.junit.runners.Suite;4import org.junit.runners.Suite.SuiteClasses;5import org.junit.runners.model.AllModelTests;6import org.junit.runners.parameterized.AllParameterizedTests;7@RunWith(Suite.class)8@SuiteClasses({9 AllModelTests.class,10 AllParameterizedTests.class,11 RuleContainerTest.class,12 CustomBlockJUnit4ClassRunnerTest.class13})14public class AllRunnersTests {15}...
Parameterized
Using AI Code Generation
1import static org.junit.Assert.assertEquals;2import java.util.Arrays;3import java.util.Collection;4import org.junit.Test;5import org.junit.runner.RunWith;6import org.junit.runners.Parameterized;7import org.junit.runners.Parameterized.Parameters;8@RunWith(Parameterized.class)9public class TestParameterized {10 private int input;11 private int expected;12 public TestParameterized(int input, int expected) {13 this.input = input;14 this.expected = expected;15 }16 public static Collection<Object[]> data() {17 Object[][] data = new Object[][] {{1,2}, {5,6}, {121,122}};18 return Arrays.asList(data);19 }20 public void test() {21 assertEquals(expected, new MyClass().addOne(input));22 }23}24class MyClass {25 public int addOne(int x) {26 return x+1;27 }28}
Parameterized
Using AI Code Generation
1package com.journaldev.junit;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.junit.runners.Parameterized;5import org.junit.runners.Parameterized.Parameters;6import java.util.Arrays;7import java.util.Collection;8import static org.junit.Assert.assertEquals;9@RunWith(Parameterized.class)10public class TestParameterized {11 private int number1;12 private int number2;13 private int expected;14 public TestParameterized(int number1, int number2, int expected) {15 this.number1 = number1;16 this.number2 = number2;17 this.expected = expected;18 }19 public static Collection<Object[]> data() {20 Object[][] data = new Object[][] { { 1, 2, 3 }, { 5, 3, 8 }, { 121, 4, 125 }, { 11, 9, 20 } };21 return Arrays.asList(data);22 }23 public void testAdd() {24 assertEquals(expected, new Calculator().add(number1, number2));25 }26}
Parameterized
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 TestWithParameters {9 private int number;10 public TestWithParameters(int number) {11 this.number = number;12 }13 public static Collection<Object[]> data() {14 Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };15 return Arrays.asList(data);16 }17 public void test() {18 System.out.println("Parameterized Number is : " + number);19 }20}
Parameterized
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestClass {3 private int input;4 private int expected;5 public TestClass(int input, int expected) {6 this.input = input;7 this.expected = expected;8 }9 public static Collection<Object[]> data() {10 return Arrays.asList(new Object[][] {11 { 1, 2 },12 { 2, 4 },13 { 8, 16 }14 });15 }16 public void test() {17 assertEquals(expected, new MyClass().doubleTheNumber(input));18 }19}20public class MyClass {21 public int doubleTheNumber(int number) {22 return number * 2;23 }24}25OK (1 test)
Parameterized
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestParameterized {3 private int number;4 public TestParameterized(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}
Parameterized
Using AI Code Generation
1@RunWith(Parameterized.class)2public class TestParameterized {3 private String expected;4 private String actual;5 public TestParameterized(String expected, String actual) {6 this.expected = expected;7 this.actual = actual;8 }9 public static Collection<String[]> getTestParameters() {10 return Arrays.asList(new String[][] {11 {"Hello", "Hello"},12 {"World", "World"}13 });14 }15 public void test() {16 assertEquals(expected, actual);17 }18}
JUnit 4 Expected Exception type
java: how to mock Calendar.getInstance()?
Changing names of parameterized tests
Mocking a class vs. mocking its interface
jUnit ignore @Test methods from base class
Important frameworks/tools to learn
Unit testing a Java Servlet
Meaning of delta or epsilon argument of assertEquals for double values
Different teardown for each @Test in jUnit
Best way to automagically migrate tests from JUnit 3 to JUnit 4?
There's actually an alternative to the @Test(expected=Xyz.class)
in JUnit 4.7 using Rule
and ExpectedException
In your test case you declare an ExpectedException
annotated with @Rule
, and assign it a default value of ExpectedException.none()
. Then in your test that expects an exception you replace the value with the actual expected value. The advantage of this is that without using the ugly try/catch method, you can further specify what the message within the exception was
@Rule public ExpectedException thrown= ExpectedException.none();
@Test
public void myTest() {
thrown.expect( Exception.class );
thrown.expectMessage("Init Gold must be >= 0");
rodgers = new Pirate("Dread Pirate Rodgers" , -100);
}
Using this method, you might be able to test for the message in the generic exception to be something specific.
ADDITION
Another advantage of using ExpectedException
is that you can more precisely scope the exception within the context of the test case. If you are only using @Test(expected=Xyz.class)
annotation on the test, then the Xyz exception can be thrown anywhere in the test code -- including any test setup or pre-asserts within the test method. This can lead to a false positive.
Using ExpectedException, you can defer specifying the thrown.expect(Xyz.class)
until after any setup and pre-asserts, just prior to actually invoking the method under test. Thus, you more accurately scope the exception to be thrown by the actual method invocation rather than any of the test fixture itself.
JUnit 5 NOTE:
JUnit 5 JUnit Jupiter has removed @Test(expected=...)
, @Rule
and ExpectedException
altogether. They are replaced with the new assertThrows()
, which requires the use of Java 8 and lambda syntax. ExpectedException
is still available for use in JUnit 5 through JUnit Vintage. Also JUnit Jupiter will also continue to support JUnit 4 ExpectedException
through use of the junit-jupiter-migrationsupport module, but only if you add an additional class-level annotation of @EnableRuleMigrationSupport
.
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium NUnit Tutorial.
There are various CI/CD tools such as CircleCI, TeamCity, Bamboo, Jenkins, GitLab, Travis CI, GoCD, etc., that help companies streamline their development process and ensure high-quality applications. If we talk about the top CI/CD tools in the market, Jenkins is still one of the most popular, stable, and widely used open-source CI/CD tools for building and automating continuous integration, delivery, and deployment pipelines smoothly and effortlessly.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium pytest Tutorial.
The Selenium automation framework supports many programming languages such as Python, PHP, Perl, Java, C#, and Ruby. But if you are looking for a server-side programming language for automation testing, Selenium WebDriver with PHP is the ideal combination.
While working on a project for test automation, you’d require all the Selenium dependencies associated with it. Usually these dependencies are downloaded and upgraded manually throughout the project lifecycle, but as the project gets bigger, managing dependencies can be quite challenging. This is why you need build automation tools such as Maven to handle them automatically.
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!!