How to use JGivenUserException class of com.tngtech.jgiven.exception package

Best JGiven code snippet using com.tngtech.jgiven.exception.JGivenUserException

Source:ScenarioExecutor.java Github

copy

Full Screen

...10import com.tngtech.jgiven.annotation.ScenarioStage;11import com.tngtech.jgiven.attachment.Attachment;12import com.tngtech.jgiven.exception.FailIfPassedException;13import com.tngtech.jgiven.exception.JGivenMissingRequiredScenarioStateException;14import com.tngtech.jgiven.exception.JGivenUserException;15import com.tngtech.jgiven.impl.inject.ValueInjector;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);...

Full Screen

Full Screen

Source:StageLifecycleManager.java Github

copy

Full Screen

2import com.tngtech.jgiven.annotation.AfterScenario;3import com.tngtech.jgiven.annotation.AfterStage;4import com.tngtech.jgiven.annotation.BeforeScenario;5import com.tngtech.jgiven.annotation.BeforeStage;6import com.tngtech.jgiven.exception.JGivenUserException;7import com.tngtech.jgiven.impl.intercept.StepInterceptorImpl;8import com.tngtech.jgiven.impl.util.ReflectionUtil;9import java.lang.annotation.Annotation;10import java.lang.reflect.Method;11import java.util.Arrays;12import java.util.HashMap;13import java.util.Map;14import java.util.Optional;15import java.util.function.Predicate;16import java.util.stream.Stream;17import org.slf4j.Logger;18import org.slf4j.LoggerFactory;19class StageLifecycleManager {20 private static final Logger log = LoggerFactory.getLogger(StageLifecycleManager.class);21 private final Object instance;22 private final StepInterceptorImpl methodInterceptor;23 private final LifecycyleMethodManager<AfterStage> afterStageRegister;24 private final LifecycyleMethodManager<BeforeStage> beforeStageRegister;25 private final LifecycyleMethodManager<BeforeScenario> beforeScenarioRegister;26 private final LifecycyleMethodManager<AfterScenario> afterScenarioRegister;27 StageLifecycleManager(Object instance, StepInterceptorImpl methodInterceptor) {28 this.methodInterceptor = methodInterceptor;29 this.instance = instance;30 afterStageRegister = new LifecycyleMethodManager<>(AfterStage.class, AfterStage::repeatable);31 beforeStageRegister = new LifecycyleMethodManager<>(BeforeStage.class, BeforeStage::repeatable);32 beforeScenarioRegister = new LifecycyleMethodManager<>(BeforeScenario.class, (it) -> false);33 afterScenarioRegister = new LifecycyleMethodManager<>(AfterScenario.class, (it) -> false);34 }35 boolean allAfterStageMethodsHaveBeenExecuted() {36 return afterStageRegister.allMethodsHaveBeenExecuted();37 }38 void executeAfterStageMethods(boolean fakeExecution) throws Throwable {39 executeLifecycleMethods(afterStageRegister, fakeExecution);40 }41 void executeBeforeStageMethods(boolean fakeExecution) throws Throwable {42 executeLifecycleMethods(beforeStageRegister, fakeExecution);43 }44 void executeAfterScenarioMethods(boolean fakeExecution) throws Throwable {45 executeLifecycleMethods(afterScenarioRegister, fakeExecution);46 }47 void executeBeforeScenarioMethods(boolean fakeExecution) throws Throwable {48 executeLifecycleMethods(beforeScenarioRegister, fakeExecution);49 }50 private void executeLifecycleMethods(LifecycyleMethodManager<?> register, boolean fakeExecution) throws Throwable {51 if (fakeExecution) {52 register.fakeExecution();53 } else {54 register.executeMethods();55 }56 }57 private enum StepExecutionState {58 EXECUTED(true),59 REPEATABLE(false),60 NOT_EXECUTED(false);61 private final boolean hasBeenExecuted;62 StepExecutionState(boolean hasBeenExecuted) {63 this.hasBeenExecuted = hasBeenExecuted;64 }65 public boolean toBoolean() {66 return this.hasBeenExecuted;67 }68 }69 private class LifecycyleMethodManager<T extends Annotation> {70 private final Class<T> targetAnnotation;71 private final Map<Method, StepExecutionState> register = new HashMap<>();72 private final Predicate<T> predicateFromT;73 private LifecycyleMethodManager(Class<T> targetAnnotation, Predicate<T> predicateFromAnnotation) {74 this.targetAnnotation = targetAnnotation;75 this.predicateFromT = predicateFromAnnotation;76 fillStageRegister(instance);77 }78 @SuppressWarnings({"unchecked"})79 private void fillStageRegister(Object instance) {80 ReflectionUtil.forEachMethod(instance, instance.getClass(), targetAnnotation,81 (object, method) ->82 Arrays.stream(method.getDeclaredAnnotations())83 .filter(annotation -> targetAnnotation.isAssignableFrom(annotation.getClass()))84 .map(annotation -> (T) annotation)85 .findFirst()86 .map(it -> predicateFromT.test(it) ? StepExecutionState.REPEATABLE :87 StepExecutionState.NOT_EXECUTED)88 .ifPresent(it -> register.put(method, it))89 );90 log.debug("Added methods '{}' as '{}' methods to the register",91 register.keySet(), targetAnnotation.getSimpleName());92 }93 boolean methodMarkedForExecution(Method method) {94 return !Optional.ofNullable(register.get(method))95 .map(StepExecutionState::toBoolean)96 .orElse(true);97 }98 boolean allMethodsHaveBeenExecuted() {99 return register.values().stream().allMatch(StepExecutionState::toBoolean);100 }101 /**102 * Do everything except method invocation.103 */104 void fakeExecution() throws Throwable {105 prepareMethods();106 doExecutionOn(Stream.of());107 }108 void executeMethods() throws Throwable {109 Stream<Method> methodsToExecute = prepareMethods();110 doExecutionOn(methodsToExecute);111 }112 private Stream<Method> prepareMethods() {113 return register.keySet().stream().filter(this::methodMarkedForExecution)114 .peek(this::markStageAsExecuted);115 }116 private void markStageAsExecuted(Method method) {117 StepExecutionState stepState = register.get(method);118 if (stepState == StepExecutionState.NOT_EXECUTED) {119 register.put(method, StepExecutionState.EXECUTED);120 }121 }122 private void doExecutionOn(Stream<Method> methodsToExecute)123 throws Throwable {124 log.debug("Executing methods annotated with @{}", targetAnnotation.getName());125 boolean previousMethodExecution = methodInterceptor.enableMethodExecution(true);126 try {127 methodInterceptor.enableMethodInterception(false);128 methodsToExecute.forEach(method ->129 ReflectionUtil.invokeMethod(instance, method,130 " with annotation @" + targetAnnotation.getName()));131 methodInterceptor.enableMethodInterception(true);132 } catch (JGivenUserException e) {133 throw e.getCause();134 } finally {135 methodInterceptor.enableMethodExecution(previousMethodExecution);136 }137 }138 }139}...

Full Screen

Full Screen

Source:JGivenUserException.java Github

copy

Full Screen

2import java.lang.reflect.Method;3/**4 * This exception is thrown when JGiven tried to execute a user-defined method and that method has thrown an exception.5 */6public class JGivenUserException extends RuntimeException {7 private static final long serialVersionUID = 1L;8 public JGivenUserException( Method method, String methodDescription, Throwable cause ) {9 super( "JGiven caught an exception while trying to execute method " + method + methodDescription + ".", cause );10 }11}...

Full Screen

Full Screen

JGivenUserException

Using AI Code Generation

copy

Full Screen

1import com.tngtech.jgiven.exception.JGivenUserException;2public class JGivenUserExceptionExample {3 public static void main(String[] args) {4 JGivenUserException jgivenUserException = new JGivenUserException("JGiven Exception");5 System.out.println(jgivenUserException.getMessage());6 }7}

Full Screen

Full Screen

JGivenUserException

Using AI Code Generation

copy

Full Screen

1public class JGivenUserExceptionExample {2 public static void main(String[] args) {3 JGivenUserException jGivenUserException = new JGivenUserException("This is a user exception");4 System.out.println(jGivenUserException.getMessage());5 }6}

Full Screen

Full Screen

JGivenUserException

Using AI Code Generation

copy

Full Screen

1import com.tngtech.jgiven.exception.JGivenUserException;2public class JGivenUserExceptionClass {3 public static void main(String[] args) {4 try {5 throw new JGivenUserException("JGivenUserException");6 }7 catch(JGivenUserException e) {8 System.out.println(e.getMessage());9 }10 }11}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run JGiven automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in JGivenUserException

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful