Best JGiven code snippet using com.tngtech.jgiven.impl.util.FieldCache
Source:ScenarioExecutor.java  
...16import com.tngtech.jgiven.impl.intercept.NoOpScenarioListener;17import com.tngtech.jgiven.impl.intercept.ScenarioListener;18import com.tngtech.jgiven.impl.intercept.StageTransitionHandler;19import com.tngtech.jgiven.impl.intercept.StepInterceptorImpl;20import com.tngtech.jgiven.impl.util.FieldCache;21import com.tngtech.jgiven.impl.util.ReflectionUtil;22import com.tngtech.jgiven.integration.CanWire;23import com.tngtech.jgiven.report.model.InvocationMode;24import com.tngtech.jgiven.report.model.NamedArgument;25import java.lang.annotation.Annotation;26import java.lang.reflect.Field;27import java.lang.reflect.Method;28import java.util.ArrayList;29import java.util.LinkedHashMap;30import java.util.List;31import java.util.Map;32import java.util.Optional;33import org.slf4j.Logger;34import org.slf4j.LoggerFactory;35/**36 * Main class of JGiven for executing scenarios.37 */38public class ScenarioExecutor {39    private static final Logger log = LoggerFactory.getLogger(ScenarioExecutor.class);40    enum State {41        INIT,42        STARTED,43        FINISHED44    }45    private Object currentTopLevelStage;46    private State state = State.INIT;47    private boolean beforeScenarioMethodsExecuted;48    /**49     * Whether life cycle methods should be executed.50     * This is only false for scenarios that are annotated with @NotImplementedYet51     */52    private boolean executeLifeCycleMethods = true;53    protected final Map<Class<?>, StageState> stages = new LinkedHashMap<>();54    private final List<Object> scenarioRules = new ArrayList<>();55    private final ValueInjector injector = new ValueInjector();56    private StageCreator stageCreator = createStageCreator(new ByteBuddyStageClassCreator());57    private ScenarioListener listener = new NoOpScenarioListener();58    protected final StageTransitionHandler stageTransitionHandler = new StageTransitionHandlerImpl();59    protected final StepInterceptorImpl methodInterceptor =60        new StepInterceptorImpl(this, listener, stageTransitionHandler);61    /**62     * Set if an exception was thrown during the execution of the scenario and63     * suppressStepExceptions is true.64     */65    private Throwable failedException;66    private boolean failIfPass;67    /**68     * Whether exceptions caught while executing steps should be thrown at the end69     * of the scenario. Only relevant if suppressStepExceptions is true, because otherwise70     * the exceptions are not caught at all.71     */72    private boolean suppressExceptions;73    /**74     * Whether exceptions thrown while executing steps should be suppressed or not.75     * Only relevant for normal executions of scenarios.76     */77    private boolean suppressStepExceptions = true;78    /**79     * Create a new ScenarioExecutor instance.80     */81    public ScenarioExecutor() {82        injector.injectValueByType(ScenarioExecutor.class, this);83        injector.injectValueByType(CurrentStep.class, new StepAccessImpl());84        injector.injectValueByType(CurrentScenario.class, new ScenarioAccessImpl());85    }86    class StepAccessImpl implements CurrentStep {87        @Override88        public void addAttachment(Attachment attachment) {89            listener.attachmentAdded(attachment);90        }91        @Override92        public void setExtendedDescription(String extendedDescription) {93            listener.extendedDescriptionUpdated(extendedDescription);94        }95        @Override96        public void setName(String name) {97            listener.stepNameUpdated(name);98        }99        @Override100        public void setComment(String comment) {101            listener.stepCommentUpdated(comment);102        }103    }104    class ScenarioAccessImpl implements CurrentScenario {105        @Override106        public void addTag(Class<? extends Annotation> annotationClass, String... values) {107            listener.tagAdded(annotationClass, values);108        }109    }110    class StageTransitionHandlerImpl implements StageTransitionHandler {111        @Override112        public void enterStage(Object parentStage, Object childStage) throws Throwable {113            if (parentStage == childStage || currentTopLevelStage == childStage) { // NOSONAR: reference comparison OK114                return;115            }116            // if currentStage == null, this means that no stage at117            // all has been executed, thus we call all beforeScenarioMethods118            if (currentTopLevelStage == null) {119                ensureBeforeScenarioMethodsAreExecuted();120            } else {121                // in case parentStage == null, this is the first top-level122                // call on this stage, thus we have to call the afterStage methods123                // from the current top level stage124                if (parentStage == null) {125                    executeAfterStageMethods(currentTopLevelStage);126                    readScenarioState(currentTopLevelStage);127                } else {128                    // as the parent stage is not null, we have a true child call129                    // thus we have to read the state from the parent stage130                    readScenarioState(parentStage);131                    // if there has been a child stage that was executed before132                    // and the new child stage is different, we have to execute133                    // the after stage methods of the previous child stage134                    StageState stageState = getStageState(parentStage);135                    if (stageState.currentChildStage != null && stageState.currentChildStage != childStage136                        && !afterStageMethodsCalled(stageState.currentChildStage)) {137                        updateScenarioState(stageState.currentChildStage);138                        executeAfterStageMethods(stageState.currentChildStage);139                        readScenarioState(stageState.currentChildStage);140                    }141                    stageState.currentChildStage = childStage;142                }143            }144            updateScenarioState(childStage);145            executeBeforeStageMethods(childStage);146            if (parentStage == null) {147                currentTopLevelStage = childStage;148            }149        }150        @Override151        public void leaveStage(Object parentStage, Object childStage) throws Throwable {152            if (parentStage == childStage || parentStage == null) {153                return;154            }155            readScenarioState(childStage);156            // in case we leave a child stage that itself had a child stage157            // we have to execute the after stage method of that transitive child158            StageState childState = getStageState(childStage);159            if (childState.currentChildStage != null) {160                updateScenarioState(childState.currentChildStage);161                if (!getStageState(childState.currentChildStage).allAfterStageMethodsHaveBeenExecuted()) {162                    executeAfterStageMethods(childState.currentChildStage);163                    readScenarioState(childState.currentChildStage);164                    updateScenarioState(childStage);165                }166                childState.currentChildStage = null;167            }168            updateScenarioState(parentStage);169        }170    }171    @SuppressWarnings("unchecked")172    <T> T addStage(Class<T> stageClass) {173        if (stages.containsKey(stageClass)) {174            return (T) stages.get(stageClass).instance;175        }176        T result = stageCreator.createStage(stageClass, methodInterceptor);177        methodInterceptor.enableMethodInterception(true);178        stages.put(stageClass, new StageState(result, methodInterceptor));179        gatherRules(result);180        injectStages(result);181        return result;182    }183    public void addIntroWord(String word) {184        listener.introWordAdded(word);185    }186    @SuppressWarnings("unchecked")187    private void gatherRules(Object stage) {188        for (Field field : FieldCache.get(stage.getClass()).getFieldsWithAnnotation(ScenarioRule.class)) {189            log.debug("Found rule in field {} ", field);190            try {191                scenarioRules.add(field.get(stage));192            } catch (IllegalAccessException e) {193                throw new RuntimeException("Error while reading field " + field, e);194            }195        }196    }197    private <T> void updateScenarioState(T t) {198        try {199            injector.updateValues(t);200        } catch (JGivenMissingRequiredScenarioStateException e) {201            if (!suppressExceptions) {202                throw e;203            }204        }205    }206    private boolean afterStageMethodsCalled(Object stage) {207        return getStageState(stage).allAfterStageMethodsHaveBeenExecuted();208    }209    //TODO: nicer stage search?210    // What may happen if there is a common superclass to two distinct implementations? Is that even possible?211    StageState getStageState(Object stage) {212        Class<?> stageClass = stage.getClass();213        StageState stageState = stages.get(stageClass);214        while (stageState == null && stageClass != stageClass.getSuperclass()) {215            stageState = stages.get(stageClass);216            stageClass = stageClass.getSuperclass();217        }218        return stageState;219    }220    private void ensureBeforeScenarioMethodsAreExecuted() throws Throwable {221        if (state != State.INIT) {222            return;223        }224        state = STARTED;225        methodInterceptor.enableMethodInterception(false);226        try {227            for (Object rule : scenarioRules) {228                invokeRuleMethod(rule, "before");229            }230            beforeScenarioMethodsExecuted = true;231            for (StageState stage : stages.values()) {232                executeBeforeScenarioMethods(stage.instance);233            }234        } catch (Throwable e) {235            failed(e);236            finished();237            throw e;238        }239        methodInterceptor.enableMethodInterception(true);240    }241    private void invokeRuleMethod(Object rule, String methodName) throws Throwable {242        if (!executeLifeCycleMethods) {243            return;244        }245        Optional<Method> optionalMethod = ReflectionUtil.findMethodTransitively(rule.getClass(), methodName);246        if (!optionalMethod.isPresent()) {247            log.debug("Class {} has no {} method, but was used as ScenarioRule!", rule.getClass(), methodName);248            return;249        }250        try {251            ReflectionUtil.invokeMethod(rule, optionalMethod.get(), " of rule class " + rule.getClass().getName());252        } catch (JGivenUserException e) {253            throw e.getCause();254        }255    }256    private void executeBeforeScenarioMethods(Object stage) throws Throwable {257        getStageState(stage).executeBeforeScenarioMethods(!executeLifeCycleMethods);258    }259    private void executeBeforeStageMethods(Object stage) throws Throwable {260        getStageState(stage).executeBeforeStageMethods(!executeLifeCycleMethods);261    }262    private void executeAfterStageMethods(Object stage) throws Throwable {263        getStageState(stage).executeAfterStageMethods(!executeLifeCycleMethods);264    }265    private void executeAfterScenarioMethods(Object stage) throws Throwable {266        getStageState(stage).executeAfterScenarioMethods(!executeLifeCycleMethods);267    }268    public void readScenarioState(Object object) {269        injector.readValues(object);270    }271    /**272     * Used for DI frameworks to inject values into stages.273     */274    public void wireSteps(CanWire canWire) {275        for (StageState steps : stages.values()) {276            canWire.wire(steps.instance);277        }278    }279    /**280     * Has to be called when the scenario is finished in order to execute after methods.281     */282    public void finished() throws Throwable {283        if (state == FINISHED) {284            return;285        }286        State previousState = state;287        state = FINISHED;288        methodInterceptor.enableMethodInterception(false);289        try {290            if (previousState == STARTED) {291                callFinishLifeCycleMethods();292            }293        } finally {294            listener.scenarioFinished();295        }296    }297    private void callFinishLifeCycleMethods() throws Throwable {298        Throwable firstThrownException = failedException;299        if (beforeScenarioMethodsExecuted) {300            try {301                if (currentTopLevelStage != null) {302                    executeAfterStageMethods(currentTopLevelStage);303                }304            } catch (Exception e) {305                firstThrownException = logAndGetFirstException(firstThrownException, e);306            }307            for (StageState stage : reverse(newArrayList(stages.values()))) {308                try {309                    executeAfterScenarioMethods(stage.instance);310                } catch (Exception e) {311                    firstThrownException = logAndGetFirstException(firstThrownException, e);312                }313            }314        }315        for (Object rule : reverse(scenarioRules)) {316            try {317                invokeRuleMethod(rule, "after");318            } catch (Exception e) {319                firstThrownException = logAndGetFirstException(firstThrownException, e);320            }321        }322        failedException = firstThrownException;323        if (!suppressExceptions && failedException != null) {324            throw failedException;325        }326        if (failIfPass && failedException == null) {327            throw new FailIfPassedException();328        }329    }330    private Throwable logAndGetFirstException(Throwable firstThrownException, Throwable newException) {331        log.error(newException.getMessage(), newException);332        return firstThrownException == null ? newException : firstThrownException;333    }334    /**335     * Initialize the fields annotated with {@link ScenarioStage} in the test class.336     */337    @SuppressWarnings("unchecked")338    public void injectStages(Object stage) {339        for (Field field : FieldCache.get(stage.getClass()).getFieldsWithAnnotation(ScenarioStage.class)) {340            Object steps = addStage(field.getType());341            ReflectionUtil.setField(field, stage, steps, ", annotated with @ScenarioStage");342        }343    }344    public boolean hasFailed() {345        return failedException != null;346    }347    public Throwable getFailedException() {348        return failedException;349    }350    public void setFailedException(Exception e) {351        failedException = e;352    }353    /**...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}...FieldCache
Using AI Code Generation
1import com.tngtech.jgiven.annotation.*;2import com.tngtech.jgiven.impl.util.*;3import com.tngtech.jgiven.junit.*;4import org.junit.*;5import org.junit.runner.*;6import static org.junit.Assert.*;7import java.lang.reflect.*;8import java.util.*;9import java.util.stream.*;10import java.util.stream.Collectors.*;11@RunWith( JGivenClassRunner.class )12public class FieldCacheTest extends JGivenBaseTest<GivenTestStage, WhenTestStage, ThenTestStage> {13    public void test() throws Exception {14        FieldCache cache = new FieldCache( TestClass.class );15        List<Field> fields = cache.getFields();16        then().the_list_of_fields( fields );17    }18    public static class TestClass {19        public int a;20        public int b;21        public int c;22    }23}24import com.tngtech.jgiven.annotation.*;25import com.tngtech.jgiven.impl.util.*;26import com.tngtech.jgiven.junit.*;27import org.junit.*;28import org.junit.runner.*;29import static org.junit.Assert.*;30import java.lang.reflect.*;31import java.util.*;32import java.util.stream.*;33import java.util.stream.Collectors.*;34@RunWith( JGivenClassRunner.class )35public class FieldCacheTest extends JGivenBaseTest<GivenTestStage, WhenTestStage, ThenTestStage> {36    public void test() throws Exception {37        FieldCache cache = new FieldCache( TestClass.class );38        List<Field> fields = cache.getFields();39        then().the_list_of_fields( fields );40    }41    public static class TestClass {42        public int a;43        public int b;44        public int c;45    }46}47import com.tngtech.jgiven.annotation.*;48import com.tngtech.jgiven.impl.util.*;49import com.tngtech.jgiven.junit.*;50import org.junit.*;51import org.junit.runner.*;52import static org.junit.Assert.*;53import java.lang.reflect.*;54import java.util.*;55import java.util.stream.*;56import java.util.stream.Collectors.*;57@RunWith( JGivenClassRunner.class )58public class FieldCacheTest extends JGivenBaseTest<GivenTestStage, WhenTestStage, ThenTestStage> {59    public void test() throws Exception {FieldCache
Using AI Code Generation
1import com.tngtech.jgiven.impl.util.FieldCache;2public class Main {3    public static void main(String[] args) {4        FieldCache cache = new FieldCache();5        System.out.println(cache);6    }7}8Exception in thread "main" java.lang.IllegalAccessError: tried to access method com.tngtech.jgiven.impl.util.FieldCache.<init>()V from class Main9	at Main.main(Main.java:7)FieldCache
Using AI Code Generation
1import com.tngtech.jgiven.impl.util.FieldCache;2import org.junit.Test;3import java.lang.reflect.Field;4{5public void testFieldCache() throws Exception6{7FieldCache fieldCache = new FieldCache();8Field field = fieldCache.getField(MyClass.class, "field1");9System.out.println("field1 = " + field);10field = fieldCache.getField(MyClass.class, "field2");11System.out.println("field2 = " + field);12field = fieldCache.getField(MyClass.class, "field3");13System.out.println("field3 = " + field);14}15{16public String field1;17public String field2;18public String field3;19}20}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!!
