Best junit code snippet using org.junit.experimental.theories.PotentialAssignment
Source: AllMembersSupplier.java
...10import org.junit.experimental.theories.DataPoint;11import org.junit.experimental.theories.DataPoints;12import org.junit.experimental.theories.ParameterSignature;13import org.junit.experimental.theories.ParameterSupplier;14import org.junit.experimental.theories.PotentialAssignment;15import org.junit.runners.model.FrameworkMethod;16import org.junit.runners.model.TestClass;17/**18 * Supplies Theory parameters based on all public members of the target class.19 */20public class AllMembersSupplier extends ParameterSupplier {21 static class MethodParameterValue extends PotentialAssignment {22 private final FrameworkMethod fMethod;23 private MethodParameterValue(FrameworkMethod dataPointMethod) {24 fMethod= dataPointMethod;25 }26 @Override27 public Object getValue() throws CouldNotGenerateValueException {28 try {29 return fMethod.invokeExplosively(null);30 } catch (IllegalArgumentException e) {31 throw new RuntimeException(32 "unexpected: argument length is checked");33 } catch (IllegalAccessException e) {34 throw new RuntimeException(35 "unexpected: getMethods returned an inaccessible method");36 } catch (Throwable e) {37 throw new CouldNotGenerateValueException();38 // do nothing, just look for more values39 }40 }41 @Override42 public String getDescription() throws CouldNotGenerateValueException {43 return fMethod.getName();44 }45 }46 private final TestClass fClass;47 /**48 * Constructs a new supplier for {@code type}49 */50 public AllMembersSupplier(TestClass type) {51 fClass= type;52 }53 @Override54 public List<PotentialAssignment> getValueSources(ParameterSignature sig) {55 List<PotentialAssignment> list= new ArrayList<PotentialAssignment>();56 addFields(sig, list);57 addSinglePointMethods(sig, list);58 addMultiPointMethods(list);59 return list;60 }61 private void addMultiPointMethods(List<PotentialAssignment> list) {62 for (FrameworkMethod dataPointsMethod : fClass63 .getAnnotatedMethods(DataPoints.class))64 try {65 addArrayValues(dataPointsMethod.getName(), list, dataPointsMethod.invokeExplosively(null));66 } catch (Throwable e) {67 // ignore and move on68 }69 }70 @SuppressWarnings("deprecation")71 private void addSinglePointMethods(ParameterSignature sig,72 List<PotentialAssignment> list) {73 for (FrameworkMethod dataPointMethod : fClass74 .getAnnotatedMethods(DataPoint.class)) {75 Class<?> type= sig.getType();76 if ((dataPointMethod.producesType(type)))77 list.add(new MethodParameterValue(dataPointMethod));78 }79 }80 private void addFields(ParameterSignature sig,81 List<PotentialAssignment> list) {82 for (final Field field : fClass.getJavaClass().getFields()) {83 if (Modifier.isStatic(field.getModifiers())) {84 Class<?> type= field.getType();85 if (sig.canAcceptArrayType(type)86 && field.getAnnotation(DataPoints.class) != null) {87 addArrayValues(field.getName(), list, getStaticFieldValue(field));88 } else if (sig.canAcceptType(type)89 && field.getAnnotation(DataPoint.class) != null) {90 list.add(PotentialAssignment91 .forValue(field.getName(), getStaticFieldValue(field)));92 }93 }94 }95 }96 private void addArrayValues(String name, List<PotentialAssignment> list, Object array) {97 for (int i= 0; i < Array.getLength(array); i++)98 list.add(PotentialAssignment.forValue(name + "[" + i + "]", Array.get(array, i)));99 }100 private Object getStaticFieldValue(final Field field) {101 try {102 return field.get(null);103 } catch (IllegalArgumentException e) {104 throw new RuntimeException(105 "unexpected: field from getClass doesn't exist on object");106 } catch (IllegalAccessException e) {107 throw new RuntimeException(108 "unexpected: getFields returned an inaccessible field");109 }110 }111}...
Source: CustomSuplierTests.java
...11import java.util.List;12import org.junit.experimental.theories.ParameterSignature;13import org.junit.experimental.theories.ParameterSupplier;14import org.junit.experimental.theories.ParametersSuppliedBy;15import org.junit.experimental.theories.PotentialAssignment;16import org.junit.experimental.theories.Theories;17import org.junit.experimental.theories.Theory;18import org.junit.runner.RunWith;19import org.slf4j.Logger;20import org.slf4j.LoggerFactory;21// https://github.com/junit-team/junit4/wiki/Theories22@RunWith(Theories.class)23public class CustomSuplierTests {24 25 private static final Logger LOG = LoggerFactory.getLogger(CustomSuplierTests.class); 26 @Retention(RetentionPolicy.RUNTIME)27 @ParametersSuppliedBy(PrimeNumberSupplier.class)28 public @interface PrimeNumber {29 30 int start();31 32 int count();33 }34 35 public static class PrimeNumberSupplier extends ParameterSupplier {36 @Override37 public List<PotentialAssignment> getValueSources(ParameterSignature sig) throws Throwable {38 PrimeNumber annotation = (PrimeNumber) sig.getAnnotation(PrimeNumber.class);39 List<PotentialAssignment> list = new ArrayList<>();40 int nextValue = annotation.start();41 // check the first possible value42 nextValue = nextValue < 3 ? 3 : nextValue - 1;43 int count = annotation.count();44 // generate desired number of prime values45 while (count > 0) {46 nextValue++;47 if (!isPrime(nextValue)) {48 LOG.debug("Skipped number {}", nextValue);49 continue;50 }51 LOG.info("Adding prime number {}", nextValue);52 list.add(PotentialAssignment.forValue("ints", nextValue));53 count--;54 }55 return list;56 }57 58 /**59 * Checks to see if the requested value is prime.60 * @see http://stackoverflow.com/questions/24006143/generating-a-random-prime-number-in-java61 */62 public static boolean isPrime(int inputNum){63 if (inputNum <= 3 || inputNum % 2 == 0) 64 return inputNum == 2 || inputNum == 3; //this returns false if number is <=1 & true if number = 2 or 365 int divisor = 3;66 while ((divisor <= Math.sqrt(inputNum)) && (inputNum % divisor != 0)) ...
Source: WebDriverSuppliers.java
1package amazon.framework.core;2import org.junit.experimental.theories.ParameterSignature;3import org.junit.experimental.theories.ParameterSupplier;4import org.junit.experimental.theories.ParametersSuppliedBy;5import org.junit.experimental.theories.PotentialAssignment;6import java.lang.annotation.Retention;7import java.lang.annotation.RetentionPolicy;8import java.util.ArrayList;9import java.util.List;10public class WebDriverSuppliers {11 /**12 * Execute the test with multiple browsers while using the JUnit Theories runtime13 *14 * @author Nicolas Rémond (nre)15 */16 @Retention(RetentionPolicy.RUNTIME)17 @ParametersSuppliedBy(AllWebDriversSupplier.class)18 public @interface AllWebDrivers {19 }20 public static class AllWebDriversSupplier extends ParameterSupplier {21 @Override22 public List<PotentialAssignment> getValueSources(final ParameterSignature sig) {23 final List<PotentialAssignment> assignments = new ArrayList<PotentialAssignment>();24 assignments.add(PotentialAssignment.forValue(AbstractWebDriverTestCase.WebDriverKind.Chrome.toString(), AbstractWebDriverTestCase.WebDriverKind.Chrome));25 return assignments;26 }27 }28 @Retention(RetentionPolicy.RUNTIME)29 @ParametersSuppliedBy(SingleWebDriverSupplier.class)30 public @interface SingleWebDriver {31 }32 public static class SingleWebDriverSupplier extends ParameterSupplier {33 @Override34 public List<PotentialAssignment> getValueSources(final ParameterSignature sig) {35 final List<PotentialAssignment> assignments = new ArrayList<PotentialAssignment>();36 assignments.add(PotentialAssignment.forValue(AbstractWebDriverTestCase.WebDriverKind.Chrome.toString(), AbstractWebDriverTestCase.WebDriverKind.Chrome));37 return assignments;38 }39 }40}...
Source: ParameterSupplier.java
...19 * }20 *21 * public static class BetweenSupplier extends <b>ParameterSupplier</b> {22 * @Override23 * public List<<b>PotentialAssignment</b>> getValueSources(<b>ParameterSignature</b> sig) {24 * List<<b>PotentialAssignment</b>> list = new ArrayList<PotentialAssignment>();25 * Between annotation = (Between) sig.getSupplierAnnotation();26 *27 * for (int i = annotation.first(); i <= annotation.last(); i++)28 * list.add(<b>PotentialAssignment</b>.forValue("ints", i));29 * return list;30 * }31 * }32 * </pre>33 * </p>34 *35 * @see org.junit.experimental.theories.ParametersSuppliedBy36 * @see org.junit.experimental.theories.Theories37 * @see org.junit.experimental.theories.FromDataPoints38 */39public abstract class ParameterSupplier {40 public abstract List<PotentialAssignment> getValueSources(ParameterSignature sig) throws Throwable;41}...
Source: TestedOnSupplier.java
2import java.util.ArrayList;3import java.util.List;4import org.junit.experimental.theories.ParameterSignature;5import org.junit.experimental.theories.ParameterSupplier;6import org.junit.experimental.theories.PotentialAssignment;7/**8 * @see org.junit.experimental.theories.suppliers.TestedOn9 * @see org.junit.experimental.theories.ParameterSupplier10 */11public class TestedOnSupplier extends ParameterSupplier {12 @Override13 public List<PotentialAssignment> getValueSources(ParameterSignature sig) {14 List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();15 TestedOn testedOn = sig.getAnnotation(TestedOn.class);16 int[] ints = testedOn.ints();17 for (final int i : ints) {18 list.add(PotentialAssignment.forValue("ints", i));19 }20 return list;21 }22}...
Source: NumberSupplier.java
1package com.packtpub.junit.recap;2import org.junit.experimental.theories.ParameterSignature;3import org.junit.experimental.theories.ParameterSupplier;4import org.junit.experimental.theories.PotentialAssignment;5import java.util.ArrayList;6import java.util.List;7public class NumberSupplier extends ParameterSupplier {8 @Override9 public List<PotentialAssignment>10 getValueSources(ParameterSignature sig) {11 List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();12 list.add(PotentialAssignment.forValue("long", 2L));13 list.add(PotentialAssignment.forValue("float", 5.00f));14 list.add(PotentialAssignment.forValue("double", 89d));15 return list;16 }17};...
Source: StringSupplier.java
1package learn.mutumju.ch01recall;2import org.junit.experimental.theories.ParameterSignature;3import org.junit.experimental.theories.ParameterSupplier;4import org.junit.experimental.theories.PotentialAssignment;5import java.util.ArrayList;6import java.util.List;7public class StringSupplier extends ParameterSupplier {8 @Override9 public List<PotentialAssignment> getValueSources(ParameterSignature sig) {10 List<PotentialAssignment> list = new ArrayList<>();11 list.add(PotentialAssignment.forValue("name1", "one"));12 list.add(PotentialAssignment.forValue("name2", "two"));13 list.add(PotentialAssignment.forValue("name3", "three"));14 return list;15 }16}...
Source: TestedOnBoolSupplier.java
1package org.wikipedia.test.theories;2import org.junit.experimental.theories.ParameterSignature;3import org.junit.experimental.theories.ParameterSupplier;4import org.junit.experimental.theories.PotentialAssignment;5import java.util.Arrays;6import java.util.List;7public class TestedOnBoolSupplier extends ParameterSupplier {8 private static final String NAME = "bools";9 @Override public List<PotentialAssignment> getValueSources(ParameterSignature sig) {10 return Arrays.asList(PotentialAssignment.forValue(NAME, false),11 PotentialAssignment.forValue(NAME, true));12 }13}...
PotentialAssignment
Using AI Code Generation
1import org.junit.experimental.theories.*;2import org.junit.experimental.theories.PotentialAssignment;3import org.junit.experimental.theories.ParameterSignature;4import org.junit.experimental.theories.ParameterSupplier;5import org.junit.experimental.theories.Theories;6import org.junit.experimental.theories.Theory;7import org.junit.runner.RunWith;8import java.util.ArrayList;9import java.util.List;10@RunWith(Theories.class)11public class TestTheory {12 public void testTheory(String s, String t) {13 System.out.println("s="+s+", t="+t);14 }15 public static String[] dataPoints = {"a", "b", "c"};16 public static List<String> dataPoints2 = new ArrayList<String>() {{17 add("d");18 add("e");19 add("f");20 }};21 public static PotentialAssignment[] dataPoints3 = {22 PotentialAssignment.forValue("g", "g"),23 PotentialAssignment.forValue("h", "h"),24 PotentialAssignment.forValue("i", "i"),25 };26 public static ParameterSupplier dataPoints4 = new ParameterSupplier() {27 public List<PotentialAssignment> getValueSources(ParameterSignature sig) {28 List<PotentialAssignment> list = new ArrayList<>();29 list.add(PotentialAssignment.forValue("j", "j"));30 list.add(PotentialAssignment.forValue("k", "k"));31 list.add(PotentialAssignment.forValue("l", "l"));32 return list;33 }34 };35}
PotentialAssignment
Using AI Code Generation
1import java.util.ArrayList;2import java.util.List;3import org.junit.experimental.theories.PotentialAssignment;4public class MyDataPoints {5 public static List<PotentialAssignment> getMyDataPoints() {6 List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();7 list.add(PotentialAssignment.forValue("a", 1));8 list.add(PotentialAssignment.forValue("a", 2));9 list.add(PotentialAssignment.forValue("a", 3));10 return list;11 }12}13import org.junit.experimental.theories.DataPoint;14import org.junit.experimental.theories.Theory;15public class MyTheoryTest {16 public static int x = 1;17 public static int y = 2;18 public static int z = 3;19 public void test(int a) {20 System.out.println(a);21 }22}23import org.junit.experimental.theories.DataPoints;24import org.junit.experimental.theories.Theory;25public class MyTheoryTest2 {26 public static int[] data = new int[] { 1, 2, 3 };27 public void test(int a) {28 System.out.println(a);29 }30}31import org.junit.experimental.theories.DataPoint;32import org.junit.experimental.theories.Theory;33import org.junit.experimental.theories.suppliers.TestedOn;34public class MyTheoryTest3 {35 public static int x = 1;36 public static int y = 2;37 public static int z = 3;38 public void test(@TestedOn(ints = { 1, 2, 3 }) int a) {39 System.out.println(a);40 }41}42import org.junit.experimental.theories.DataPoint;43import org.junit.experimental.theories.Theory;44import org.junit.experimental.theories.suppliers.TestedOn;45public class MyTheoryTest4 {
PotentialAssignment
Using AI Code Generation
1import org.junit.experimental.theories.PotentialAssignment;2import org.junit.experimental.theories.internal.Assignments;3public static PotentialAssignment forInt() {4}5import org.junit.experimental.theories.PotentialAssignment;6import org.junit.experimental.theories.internal.Assignments;7public static PotentialAssignment forInt() {8}9import org.junit.experimental.theories.PotentialAssignment;10import org.junit.experimental.theories.internal.Assignments;11public static PotentialAssignment forInt() {12}13import org.junit.experimental.theories.PotentialAssignment;14import org.junit.experimental.theories.internal.Assignments;15public static PotentialAssignment forInt() {16}17import org.junit.experimental.theories.PotentialAssignment;18import org.junit.experimental.theories.internal.Assignments;19public static PotentialAssignment forInt() {20}21import org.junit.experimental.theories.PotentialAssignment;22import org.junit.experimental.theories.internal.Assignments;23public static PotentialAssignment forInt() {24}25import org.junit.experimental.theories.PotentialAssignment;26import org.junit.experimental
PotentialAssignment
Using AI Code Generation
1public class PotentialAssignmentGenerator implements TestGenerator {2 private static final Logger LOGGER = Logger.getLogger(PotentialAssignmentGenerator.class.getName());3 public List<TestMethod> generateTestMethods(TestClass testClass) {4 List<TestMethod> testMethods = new ArrayList<>();5 for (FrameworkMethod frameworkMethod : testClass.getAnnotatedMethods(Test.class)) {6 List<List<PotentialAssignment>> potentialAssignments = getPotentialAssignments(frameworkMethod);7 for (List<PotentialAssignment> assignments : potentialAssignments) {8 TestMethod testMethod = new TestMethod(frameworkMethod, testClass);9 for (PotentialAssignment assignment : assignments) {10 testMethod.addParameter(assignment.getValue());11 }12 testMethods.add(testMethod);13 }14 }15 return testMethods;16 }17 private List<List<PotentialAssignment>> getPotentialAssignments(FrameworkMethod frameworkMethod) {18 List<ParameterSource> parameterSources = getParameterSources(frameworkMethod);19 List<List<PotentialAssignment>> potentialAssignments = parameterSources.stream()20 .map(ParameterSource::getValueSources)21 .collect(Collectors.toList());22 return Lists.cartesianProduct(potentialAssignments);23 }24 private List<ParameterSource> getParameterSources(FrameworkMethod frameworkMethod) {25 List<ParameterSource> parameterSources = new ArrayList<>();26 for (Annotation[] parameterAnnotations : frameworkMethod.getMethod().getParameterAnnotations()) {27 for (Annotation annotation : parameterAnnotations) {28 ParameterSource parameterSource = getParameterSource(annotation);29 if (parameterSource != null) {30 parameterSources.add(parameterSource);31 }32 }33 }34 return parameterSources;35 }36 private ParameterSource getParameterSource(Annotation annotation) {37 if (annotation instanceof DataPoint) {38 return new DataPointParameterSource((DataPoint) annotation);39 } else if (annotation instanceof DataPoints) {40 return new DataPointsParameterSource((DataPoints) annotation);41 } else if (annotation instanceof FromDataPoints) {
PotentialAssignment
Using AI Code Generation
1import java.util.ArrayList;2import java.util.List;3import org.junit.experimental.theories.PotentialAssignment;4public class TestClass {5 public void testTheory(int x, int y, int z) {6 System.out.println("x = " + x + ", y = " + y + ", z = " + z);7 }8 public static List<PotentialAssignment> x() {9 List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();10 list.add(PotentialAssignment.forValue("x", 1));11 list.add(PotentialAssignment.forValue("x", 2));12 list.add(PotentialAssignment.forValue("x", 3));13 return list;14 }15 public static List<PotentialAssignment> y() {16 List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();17 list.add(PotentialAssignment.forValue("y", 4));18 list.add(PotentialAssignment.forValue("y", 5));19 list.add(PotentialAssignment.forValue("y", 6));20 return list;21 }22 public static List<PotentialAssignment> z() {23 List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();24 list.add(PotentialAssignment.forValue("z", 7));25 list.add(PotentialAssignment.forValue("z", 8));26 list.add(PotentialAssignment.forValue("z", 9));27 return list;28 }29}
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!!