Best junit code snippet using org.junit.experimental.theories.ParameterSignature
Source: AllMembersSupplier.java
...5import java.util.ArrayList;6import java.util.List;7import org.junit.experimental.theories.DataPoint;8import org.junit.experimental.theories.DataPoints;9import org.junit.experimental.theories.ParameterSignature;10import org.junit.experimental.theories.ParameterSupplier;11import org.junit.experimental.theories.PotentialAssignment;12import org.junit.runners.model.FrameworkMethod;13import org.junit.runners.model.TestClass;14/**15 * Supplies Theory parameters based on all public members of the target class.16 */17public class AllMembersSupplier extends ParameterSupplier {18 static class MethodParameterValue extends PotentialAssignment {19 private final FrameworkMethod fMethod;20 private MethodParameterValue(FrameworkMethod dataPointMethod) {21 fMethod = dataPointMethod;22 }23 @Override24 public Object getValue() throws CouldNotGenerateValueException {25 try {26 return fMethod.invokeExplosively(null);27 } catch (IllegalArgumentException e) {28 throw new RuntimeException(29 "unexpected: argument length is checked");30 } catch (IllegalAccessException e) {31 throw new RuntimeException(32 "unexpected: getMethods returned an inaccessible method");33 } catch (Throwable e) {34 throw new CouldNotGenerateValueException();35 // do nothing, just look for more values36 }37 }38 @Override39 public String getDescription() throws CouldNotGenerateValueException {40 return fMethod.getName();41 }42 }43 private final TestClass fClass;44 /**45 * Constructs a new supplier for {@code type}46 */47 public AllMembersSupplier(TestClass type) {48 fClass = type;49 }50 @Override51 public List<PotentialAssignment> getValueSources(ParameterSignature sig) {52 List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();53 addFields(sig, list);54 addSinglePointMethods(sig, list);55 addMultiPointMethods(sig, list);56 return list;57 }58 private void addMultiPointMethods(ParameterSignature sig, List<PotentialAssignment> list) {59 for (FrameworkMethod dataPointsMethod : fClass60 .getAnnotatedMethods(DataPoints.class)) {61 try {62 addMultiPointArrayValues(sig, dataPointsMethod.getName(), list, dataPointsMethod.invokeExplosively(null));63 } catch (Throwable e) {64 // ignore and move on65 }66 }67 }68 private void addSinglePointMethods(ParameterSignature sig,69 List<PotentialAssignment> list) {70 for (FrameworkMethod dataPointMethod : fClass71 .getAnnotatedMethods(DataPoint.class)) {72 if (isCorrectlyTyped(sig, dataPointMethod.getType())) {73 list.add(new MethodParameterValue(dataPointMethod));74 }75 }76 }77 private void addFields(ParameterSignature sig,78 List<PotentialAssignment> list) {79 for (final Field field : fClass.getJavaClass().getFields()) {80 if (Modifier.isStatic(field.getModifiers())) {81 Class<?> type = field.getType();82 if (sig.canAcceptArrayType(type)83 && field.getAnnotation(DataPoints.class) != null) {84 try {85 addArrayValues(field.getName(), list, getStaticFieldValue(field));86 } catch (Throwable e) {87 // ignore and move on88 }89 } else if (sig.canAcceptType(type)90 && field.getAnnotation(DataPoint.class) != null) {91 list.add(PotentialAssignment92 .forValue(field.getName(), getStaticFieldValue(field)));93 }94 }95 }96 }97 private void addArrayValues(String name, List<PotentialAssignment> list, Object array) {98 for (int i = 0; i < Array.getLength(array); i++) {99 list.add(PotentialAssignment.forValue(name + "[" + i + "]", Array.get(array, i)));100 }101 }102 private void addMultiPointArrayValues(ParameterSignature sig, String name, List<PotentialAssignment> list,103 Object array) throws Throwable {104 for (int i = 0; i < Array.getLength(array); i++) {105 if (!isCorrectlyTyped(sig, Array.get(array, i).getClass())) {106 return;107 }108 list.add(PotentialAssignment.forValue(name + "[" + i + "]", Array.get(array, i)));109 }110 }111 @SuppressWarnings("deprecation")112 private boolean isCorrectlyTyped(ParameterSignature parameterSignature, Class<?> type) {113 return parameterSignature.canAcceptType(type);114 }115 private Object getStaticFieldValue(final Field field) {116 try {117 return field.get(null);118 } catch (IllegalArgumentException e) {119 throw new RuntimeException(120 "unexpected: field from getClass doesn't exist on object");121 } catch (IllegalAccessException e) {122 throw new RuntimeException(123 "unexpected: getFields returned an inaccessible field");124 }125 }126}...
Source: Assignments.java
1package org.junit.experimental.theories.internal;2import java.lang.reflect.Method;3import java.util.ArrayList;4import java.util.List;5import org.junit.experimental.theories.ParameterSignature;6import org.junit.experimental.theories.ParameterSupplier;7import org.junit.experimental.theories.ParametersSuppliedBy;8import org.junit.experimental.theories.PotentialAssignment;9import org.junit.experimental.theories.PotentialAssignment.CouldNotGenerateValueException;10import org.junit.runners.model.TestClass;11/**12 * A potentially incomplete list of value assignments for a method's formal13 * parameters14 */15public class Assignments {16 private List<PotentialAssignment> fAssigned;17 private final List<ParameterSignature> fUnassigned;18 private final TestClass fClass;19 private Assignments(List<PotentialAssignment> assigned,20 List<ParameterSignature> unassigned, TestClass testClass) {21 fUnassigned = unassigned;22 fAssigned = assigned;23 fClass = testClass;24 }25 /**26 * Returns a new assignment list for {@code testMethod}, with no params27 * assigned.28 */29 public static Assignments allUnassigned(Method testMethod,30 TestClass testClass) throws Exception {31 List<ParameterSignature> signatures;32 signatures = ParameterSignature.signatures(testClass33 .getOnlyConstructor());34 signatures.addAll(ParameterSignature.signatures(testMethod));35 return new Assignments(new ArrayList<PotentialAssignment>(),36 signatures, testClass);37 }38 public boolean isComplete() {39 return fUnassigned.size() == 0;40 }41 public ParameterSignature nextUnassigned() {42 return fUnassigned.get(0);43 }44 public Assignments assignNext(PotentialAssignment source) {45 List<PotentialAssignment> assigned = new ArrayList<PotentialAssignment>(46 fAssigned);47 assigned.add(source);48 return new Assignments(assigned, fUnassigned.subList(1, fUnassigned49 .size()), fClass);50 }51 public Object[] getActualValues(int start, int stop, boolean nullsOk)52 throws CouldNotGenerateValueException {53 Object[] values = new Object[stop - start];54 for (int i = start; i < stop; i++) {55 Object value = fAssigned.get(i).getValue();56 if (value == null && !nullsOk) {57 throw new CouldNotGenerateValueException();58 }59 values[i - start] = value;60 }61 return values;62 }63 public List<PotentialAssignment> potentialsForNextUnassigned()64 throws InstantiationException, IllegalAccessException {65 ParameterSignature unassigned = nextUnassigned();66 return getSupplier(unassigned).getValueSources(unassigned);67 }68 public ParameterSupplier getSupplier(ParameterSignature unassigned)69 throws InstantiationException, IllegalAccessException {70 ParameterSupplier supplier = getAnnotatedSupplier(unassigned);71 if (supplier != null) {72 return supplier;73 }74 return new AllMembersSupplier(fClass);75 }76 public ParameterSupplier getAnnotatedSupplier(ParameterSignature unassigned)77 throws InstantiationException, IllegalAccessException {78 ParametersSuppliedBy annotation = unassigned79 .findDeepAnnotation(ParametersSuppliedBy.class);80 if (annotation == null) {81 return null;82 }83 return annotation.value().newInstance();84 }85 public Object[] getConstructorArguments(boolean nullsOk)86 throws CouldNotGenerateValueException {87 return getActualValues(0, getConstructorParameterCount(), nullsOk);88 }89 public Object[] getMethodArguments(boolean nullsOk)90 throws CouldNotGenerateValueException {91 return getActualValues(getConstructorParameterCount(),92 fAssigned.size(), nullsOk);93 }94 public Object[] getAllArguments(boolean nullsOk)95 throws CouldNotGenerateValueException {96 return getActualValues(0, fAssigned.size(), nullsOk);97 }98 private int getConstructorParameterCount() {99 List<ParameterSignature> signatures = ParameterSignature100 .signatures(fClass.getOnlyConstructor());101 int constructorParameterCount = signatures.size();102 return constructorParameterCount;103 }104 public Object[] getArgumentStrings(boolean nullsOk)105 throws CouldNotGenerateValueException {106 Object[] values = new Object[fAssigned.size()];107 for (int i = 0; i < values.length; i++) {108 values[i] = fAssigned.get(i).getDescription();109 }110 return values;111 }112}...
Source: SpecificDataPointsSupplier.java
...5import java.util.Collection;6import org.junit.experimental.theories.DataPoint;7import org.junit.experimental.theories.DataPoints;8import org.junit.experimental.theories.FromDataPoints;9import org.junit.experimental.theories.ParameterSignature;10import org.junit.runners.model.FrameworkMethod;11import org.junit.runners.model.TestClass;12public class SpecificDataPointsSupplier extends AllMembersSupplier {13 public SpecificDataPointsSupplier(TestClass testClass) {14 super(testClass);15 }16 /* access modifiers changed from: protected */17 public Collection<Field> getDataPointsFields(ParameterSignature parameterSignature) {18 Collection<Field> dataPointsFields = super.getDataPointsFields(parameterSignature);19 String value = ((FromDataPoints) parameterSignature.getAnnotation(FromDataPoints.class)).value();20 ArrayList arrayList = new ArrayList();21 for (Field next : dataPointsFields) {22 if (Arrays.asList(((DataPoints) next.getAnnotation(DataPoints.class)).value()).contains(value)) {23 arrayList.add(next);24 }25 }26 return arrayList;27 }28 /* access modifiers changed from: protected */29 public Collection<FrameworkMethod> getDataPointsMethods(ParameterSignature parameterSignature) {30 Collection<FrameworkMethod> dataPointsMethods = super.getDataPointsMethods(parameterSignature);31 String value = ((FromDataPoints) parameterSignature.getAnnotation(FromDataPoints.class)).value();32 ArrayList arrayList = new ArrayList();33 for (FrameworkMethod next : dataPointsMethods) {34 if (Arrays.asList(((DataPoints) next.getAnnotation(DataPoints.class)).value()).contains(value)) {35 arrayList.add(next);36 }37 }38 return arrayList;39 }40 /* access modifiers changed from: protected */41 public Collection<Field> getSingleDataPointFields(ParameterSignature parameterSignature) {42 Collection<Field> singleDataPointFields = super.getSingleDataPointFields(parameterSignature);43 String value = ((FromDataPoints) parameterSignature.getAnnotation(FromDataPoints.class)).value();44 ArrayList arrayList = new ArrayList();45 for (Field next : singleDataPointFields) {46 if (Arrays.asList(((DataPoint) next.getAnnotation(DataPoint.class)).value()).contains(value)) {47 arrayList.add(next);48 }49 }50 return arrayList;51 }52 /* access modifiers changed from: protected */53 public Collection<FrameworkMethod> getSingleDataPointMethods(ParameterSignature parameterSignature) {54 Collection<FrameworkMethod> singleDataPointMethods = super.getSingleDataPointMethods(parameterSignature);55 String value = ((FromDataPoints) parameterSignature.getAnnotation(FromDataPoints.class)).value();56 ArrayList arrayList = new ArrayList();57 for (FrameworkMethod next : singleDataPointMethods) {58 if (Arrays.asList(((DataPoint) next.getAnnotation(DataPoint.class)).value()).contains(value)) {59 arrayList.add(next);60 }61 }62 return arrayList;63 }64}...
Source: ParameterSignatureTest.java
...9import java.util.List;10import org.hamcrest.CoreMatchers;11import org.junit.Test;12import org.junit.experimental.theories.DataPoint;13import org.junit.experimental.theories.ParameterSignature;14import org.junit.experimental.theories.Theories;15import org.junit.experimental.theories.Theory;16import org.junit.experimental.theories.suppliers.TestedOn;17import org.junit.runner.RunWith;18@RunWith(Theories.class)19public class ParameterSignatureTest {20 @DataPoint21 public static Method getType() throws SecurityException,22 NoSuchMethodException {23 return ParameterSignatureTest.class.getMethod("getType", Method.class,24 int.class);25 }26 @DataPoint27 public static int ZERO = 0;28 @DataPoint29 public static int ONE = 1;30 @Theory31 public void getType(Method method, int index) {32 assumeTrue(index < method.getParameterTypes().length);33 assertEquals(method.getParameterTypes()[index], ParameterSignature34 .signatures(method).get(index).getType());35 }36 public void foo(@TestedOn(ints = {1, 2, 3}) int x) {37 }38 @Test39 public void getAnnotations() throws SecurityException,40 NoSuchMethodException {41 Method method = getClass().getMethod("foo", int.class);42 List<Annotation> annotations = ParameterSignature.signatures(method)43 .get(0).getAnnotations();44 assertThat(annotations,45 CoreMatchers.<TestedOn>hasItem(isA(TestedOn.class)));46 }47 48 public void intMethod(int param) {49 }50 51 public void integerMethod(Integer param) {52 }53 54 public void numberMethod(Number param) {55 }56 @Test57 public void primitiveTypesShouldBeAcceptedAsWrapperTypes() throws Exception {58 List<ParameterSignature> signatures = ParameterSignature59 .signatures(getClass().getMethod("integerMethod", Integer.class));60 ParameterSignature integerSignature = signatures.get(0);61 assertTrue(integerSignature.canAcceptType(int.class));62 }63 64 @Test65 public void primitiveTypesShouldBeAcceptedAsWrapperTypeAssignables() throws Exception {66 List<ParameterSignature> signatures = ParameterSignature67 .signatures(getClass().getMethod("numberMethod", Number.class));68 ParameterSignature numberSignature = signatures.get(0);69 assertTrue(numberSignature.canAcceptType(int.class));70 }71 72 @Test73 public void wrapperTypesShouldBeAcceptedAsPrimitiveTypes() throws Exception {74 List<ParameterSignature> signatures = ParameterSignature75 .signatures(getClass().getMethod("intMethod", int.class));76 ParameterSignature intSignature = signatures.get(0);77 assertTrue(intSignature.canAcceptType(Integer.class));78 }79}...
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: 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}...
ParameterSignature
Using AI Code Generation
1import org.junit.experimental.theories.ParameterSignature;2import org.junit.experimental.theories.ParameterSupplier;3import org.junit.experimental.theories.Theories;4import org.junit.experimental.theories.Theory;5import org.junit.runner.RunWith;6import java.util.ArrayList;7import java.util.Arrays;8import java.util.List;9@RunWith(Theories.class)10public class TestTheories {11 public void test(@MyParameterSupplierAnnotation int[] array) {12 System.out.println(Arrays.toString(array));13 }14}15@Retention(RetentionPolicy.RUNTIME)16@interface MyParameterSupplierAnnotation {17}18public class MyParameterSupplier extends ParameterSupplier {19 public List<Integer[]> getValueSources(ParameterSignature sig) {20 List<Integer[]> list = new ArrayList<>();21 list.add(new Integer[]{1, 2, 3});22 list.add(new Integer[]{4, 5, 6});23 return list;24 }25}
ParameterSignature
Using AI Code Generation
1import org.junit.experimental.theories.*;2import org.junit.runner.*;3@RunWith(Theories.class)4public class ParameterSignatureTest {5 public void test1(@FromDataPoints("data1") String s) {6 System.out.println(s);7 }8 public static String[] data1 = {"abc", "def", "ghi"};9}
ParameterSignature
Using AI Code Generation
1public class ParameterSignatureTest {2 public void testParameterSignature() {3 ParameterSignature parameterSignature = new ParameterSignature("name");4 assertThat(parameterSignature.getName(), is("name"));5 }6}7public class ParametersSuppliedByTest {8 public void testParametersSuppliedBy() {9 ParametersSuppliedBy parametersSuppliedBy = new ParametersSuppliedBy(Object.class);10 assertThat(parametersSuppliedBy.value(), is(Object.class));11 }12}13public class PotentialAssignmentTest {14 public void testPotentialAssignment() {15 PotentialAssignment potentialAssignment = PotentialAssignment.forValue("name", "value");16 assertThat(potentialAssignment.getDescription(), is("name"));17 assertThat(potentialAssignment.getValue(), is("value"));18 }19}20public class ParameterSignatureTest {21 public void testParameterSignature() {22 ParameterSignature parameterSignature = new ParameterSignature("name");23 assertThat(parameterSignature.getName(), is("name"));24 }25}26public class ParametersSuppliedByTest {27 public void testParametersSuppliedBy() {28 ParametersSuppliedBy parametersSuppliedBy = new ParametersSuppliedBy(Object.class);29 assertThat(parametersSuppliedBy.value(), is(Object.class));30 }31}32public class PotentialAssignmentTest {33 public void testPotentialAssignment() {34 PotentialAssignment potentialAssignment = PotentialAssignment.forValue("name", "value");35 assertThat(potentialAssignment.getDescription(), is("name"));36 assertThat(potentialAssignment.getValue(), is("value"));37 }38}39public class ParameterSignatureTest {40 public void testParameterSignature() {41 ParameterSignature parameterSignature = new ParameterSignature("name");42 assertThat(parameterSignature.getName(), is("name"));43 }44}45public class ParametersSuppliedByTest {46 public void testParametersSuppliedBy() {
ParameterSignature
Using AI Code Generation
1package com.zetcode;2import org.junit.experimental.theories.ParameterSignature;3import org.junit.experimental.theories.ParameterSupplier;4import org.junit.experimental.theories.PotentialAssignment;5import org.junit.experimental.theories.Theories;6import org.junit.experimental.theories.Theory;7import org.junit.runner.RunWith;8import java.util.Arrays;9import java.util.List;10@RunWith(Theories.class)11public class JunitTheoriesTest {12 public void testString(@StringSource String s) {13 System.out.println(s);14 }15 public static class StringSource extends ParameterSupplier {16 public List<PotentialAssignment> getValueSources(ParameterSignature sig) {17 return Arrays.asList(18 PotentialAssignment.forValue("one", "one"),19 PotentialAssignment.forValue("two", "two"),20 PotentialAssignment.forValue("three", "three")21 );22 }23 }24}25import static org.junit.Assert.*;26import org.junit.Test;27public class JunitTheoriesTest {28 public void testString() {29 fail("Not yet implemented");30 }31}
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!!