Best JGiven code snippet using com.tngtech.jgiven.impl.util.FieldCache.FieldCache
Source:ValueInjector.java
...8import com.tngtech.jgiven.exception.AmbiguousResolutionException;9import com.tngtech.jgiven.exception.JGivenInjectionException;10import com.tngtech.jgiven.exception.JGivenMissingGuaranteedScenarioStateException;11import com.tngtech.jgiven.exception.JGivenMissingRequiredScenarioStateException;12import com.tngtech.jgiven.impl.util.FieldCache;13import java.lang.reflect.Field;14import java.util.List;15import java.util.Map;16import java.util.concurrent.ConcurrentHashMap;17import org.slf4j.Logger;18import org.slf4j.LoggerFactory;19/**20 * Used by Scenario to inject and read values from objects.21 */22public class ValueInjector {23 private static final Logger log = LoggerFactory.getLogger(ValueInjector.class);24 /**25 * Caches all classes that have been already validated for ambiguous resolution.26 * This avoids duplicate validations of the same class.27 */28 private static final ConcurrentHashMap<Class<?>, Boolean> validatedClasses = new ConcurrentHashMap<>();29 private final ValueInjectorState state = new ValueInjectorState();30 /**31 * @throws AmbiguousResolutionException when multiple fields with the same resolution exist in the given object32 */33 @SuppressWarnings("unchecked")34 public void validateFields(Object object) {35 if (validatedClasses.get(object.getClass()) == Boolean.TRUE) {36 return;37 }38 Map<Object, Field> resolvedFields = Maps.newHashMap();39 for (ScenarioStateField field : getScenarioFields(object)) {40 field.getField().setAccessible(true);41 Resolution resolution = field.getResolution();42 Object key = null;43 if (resolution == Resolution.NAME) {44 key = field.getField().getName();45 } else {46 key = field.getField().getType();47 }48 if (resolvedFields.containsKey(key)) {49 Field existingField = resolvedFields.get(key);50 throw new AmbiguousResolutionException("Ambiguous fields with same " + resolution + " detected. Field 1: "51 + existingField + ", field 2: " + field.getField());52 }53 resolvedFields.put(key, field.getField());54 }55 validatedClasses.put(object.getClass(), Boolean.TRUE);56 }57 private List<ScenarioStateField> getScenarioFields(Object object) {58 @SuppressWarnings("unchecked")59 List<Field> scenarioFields = FieldCache60 .get(object.getClass())61 .getFieldsWithAnnotation(ScenarioState.class, ProvidedScenarioState.class, ExpectedScenarioState.class);62 return scenarioFields.stream()63 .map(ScenarioStateField.fromField)64 .collect(toList());65 }66 /**67 * @throws JGivenMissingGuaranteedScenarioStateException in case a field is guaranteed68 * and is not initialized by the finishing stage69 */70 @SuppressWarnings("unchecked")71 public void readValues(Object object) {72 validateFields(object);73 checkGuaranteedStatesAreInitialized(object);74 for (ScenarioStateField field : getScenarioFields(object)) {75 try {76 Object value = field.getField().get(object);77 updateValue(field, value);78 log.debug("Reading value {} from field {}", value, field.getField());79 } catch (IllegalAccessException e) {80 throw new RuntimeException("Error while reading field " + field.getField(), e);81 }82 }83 }84 /**85 * @throws JGivenMissingRequiredScenarioStateException in case a field requires86 * a value and the value is not present87 */88 @SuppressWarnings("unchecked")89 public void updateValues(Object object) {90 validateFields(object);91 for (ScenarioStateField field : getScenarioFields(object)) {92 Object value = getValue(field);93 if (value != null) {94 try {95 field.getField().set(object, value);96 } catch (IllegalAccessException e) {97 throw new RuntimeException("Error while updating field " + field.getField(), e);98 }99 log.debug("Setting field {} to value {}", field.getField(), value);100 } else if (field.isRequired()) {101 throw new JGivenMissingRequiredScenarioStateException(field.getField());102 }103 }104 }105 public <T> void injectValueByType(Class<T> clazz, T value) {106 state.updateValueByType(clazz, value);107 }108 public <T> void injectValueByName(String name, T value) {109 state.updateValueByName(name, value);110 }111 private void updateValue(ScenarioStateField field, Object value) {112 if (field.getResolution() == Resolution.NAME) {113 state.updateValueByName(field.getField().getName(), value);114 } else {115 state.updateValueByType(field.getField().getType(), value);116 }117 }118 private Object getValue(ScenarioStateField field) {119 if (field.getResolution() == Resolution.NAME) {120 return state.getValueByName(field.getField().getName());121 }122 return state.getValueByType(field.getField().getType());123 }124 private void checkGuaranteedStatesAreInitialized(Object instance) {125 for (Field field: FieldCache.get(instance.getClass())126 .getFieldsWithAnnotation(ProvidedScenarioState.class, ScenarioState.class)) {127 if (field.isAnnotationPresent(ProvidedScenarioState.class)) {128 if (field.getAnnotation(ProvidedScenarioState.class).guaranteed()) {129 checkInitialized(instance, field);130 }131 }132 if (field.isAnnotationPresent(ScenarioState.class)) {133 if (field.getAnnotation(ScenarioState.class).guaranteed()) {134 checkInitialized(instance, field);135 }136 }137 }138 }139 private void checkInitialized(Object instance, Field field) {...
Source:MockScenarioExecutor.java
...6import com.tngtech.jgiven.annotation.ScenarioStage;7import com.tngtech.jgiven.impl.ScenarioExecutor;8import com.tngtech.jgiven.impl.intercept.StageInterceptorInternal;9import com.tngtech.jgiven.impl.intercept.StepInterceptor;10import com.tngtech.jgiven.impl.util.FieldCache;11import com.tngtech.jgiven.impl.util.ReflectionUtil;12import xyz.multicatch.mockgiven.core.scenario.creator.ByteBuddyStageClassCreator;13public class MockScenarioExecutor extends ScenarioExecutor {14 private final ByteBuddyStageClassCreator byteBuddyStageClassCreator = new ByteBuddyStageClassCreator();15 @SuppressWarnings("unchecked")16 public <T> T assertInterception(17 Class<T> type,18 Object constructorParam19 ) {20 try {21 Class<? extends T> interceptableAssertion = byteBuddyStageClassCreator.createStageClass(type);22 Constructor<?>[] constructors = interceptableAssertion.getDeclaredConstructors();23 T result = null;24 for (Constructor constructor : constructors) {25 if (constructor.getParameterCount() == 1) {26 result = (T) constructor.newInstance(constructorParam);27 }28 }29 setStepInterceptor(result, methodInterceptor);30 stages.put(type, createStageState(result));31 return result;32 } catch (Error e) {33 throw e;34 } catch (Exception e) {35 throw new RuntimeException("Error while trying to create an instance of class " + type, e);36 }37 }38 protected StageState createStageState(Object instance) throws IllegalAccessException, InvocationTargetException, InstantiationException {39 Constructor<?> constructor = StageState.class.getDeclaredConstructors()[0];40 constructor.setAccessible(true);41 return (StageState) constructor.newInstance(instance);42 }43 protected <T> void setStepInterceptor(44 T result,45 StepInterceptor stepInterceptor46 ) {47 ((StageInterceptorInternal) result).__jgiven_setStepInterceptor(stepInterceptor);48 }49 @SuppressWarnings("unchecked")50 public void injectStages(Object stage) {51 for (Field field : FieldCache.get(stage.getClass())52 .getFieldsWithAnnotation(ScenarioStage.class)) {53 Object steps = addStage(field.getType());54 ReflectionUtil.setField(field, stage, steps, ", annotated with @ScenarioStage");55 }56 MockitoAnnotations.initMocks(stage);57 }58}...
Source:FieldCache.java
...8/**9 * Cache to avoid multiple expensive reflection-based look-ups10 * @since 0.7.111 */12public class FieldCache {13 private static final ConcurrentHashMap<Class<?>, FieldCache> instances = new ConcurrentHashMap<Class<?>, FieldCache>();14 public static FieldCache get( Class<?> clazz ) {15 FieldCache fieldCache = instances.get( clazz );16 if( fieldCache == null ) {17 fieldCache = new FieldCache( clazz );18 instances.put( clazz, fieldCache );19 }20 return fieldCache;21 }22 private final Class<?> clazz;23 private final ConcurrentHashMap<List<Class<? extends Annotation>>, List<Field>> fieldMap = new ConcurrentHashMap<List<Class<? extends Annotation>>, List<Field>>();24 public FieldCache( Class<?> clazz ) {25 this.clazz = clazz;26 }27 public List<Field> getFieldsWithAnnotation( final Class<? extends Annotation>... scenarioStageClasses ) {28 List<Class<? extends Annotation>> annotationList = ImmutableList.copyOf( scenarioStageClasses );29 List<Field> fields = fieldMap.get( annotationList );30 if( fields == null ) {31 final List<Field> newFields = Lists.newArrayList();32 ReflectionUtil.forEachField( null, clazz,33 ReflectionUtil.hasAtLeastOneAnnotation( scenarioStageClasses ),34 new ReflectionUtil.FieldAction() {35 @Override36 public void act( Object object, Field field ) throws Exception {37 field.setAccessible( true );38 newFields.add( field );...
FieldCache
Using AI Code Generation
1import com.tngtech.jgiven.impl.util.FieldCache;2import java.lang.reflect.Field;3import java.util.List;4public class FieldCacheExample {5 public static void main(String[] args) throws Exception {6 FieldCache fieldCache = new FieldCache();7 List<Field> fields = fieldCache.getFields(TestClass.class);8 for (Field field : fields) {9 System.out.println(field.getName());10 }11 }12}13class TestClass {14 private int i = 0;15 public int j = 0;16}
FieldCache
Using AI Code Generation
1import java.lang.reflect.Field;2public class FieldCacheTest {3 public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {4 TestObject testObject = new TestObject();5 FieldCache fieldCache = new FieldCache();6 Field field = TestObject.class.getDeclaredField("value");7 field.setAccessible(true);8 Object value = fieldCache.get(field, testObject);9 System.out.println("value = " + value);10 fieldCache.set(field, testObject, "new value");11 System.out.println("value = " + testObject.getValue());12 }13 public static class TestObject {14 private String value = "old value";15 public String getValue() {16 return value;17 }18 }19}20import java.lang.reflect.Field;21public class FieldCacheTest {22 public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {23 TestObject testObject = new TestObject();24 FieldCache fieldCache = new FieldCache();25 Field field = TestObject.class.getDeclaredField("value");26 field.setAccessible(true);27 Object value = fieldCache.get(field, testObject);28 System.out.println("value = " + value);29 fieldCache.set(field, testObject, "new value");30 System.out.println("value = " + testObject.getValue());31 }32 public static class TestObject {33 private String value = "old value";34 public String getValue() {35 return value;36 }37 }38}39import java.lang.reflect.Field;40public class FieldCacheTest {41 public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {42 TestObject testObject = new TestObject();43 FieldCache fieldCache = new FieldCache();44 Field field = TestObject.class.getDeclaredField("value");45 field.setAccessible(true);46 Object value = fieldCache.get(field, testObject);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!