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

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

Source:ReflectionUtil.java Github

copy

Full Screen

...3import com.google.common.base.Throwables;4import com.google.common.collect.Lists;5import com.tngtech.jgiven.exception.JGivenExecutionException;6import com.tngtech.jgiven.exception.JGivenInjectionException;7import com.tngtech.jgiven.exception.JGivenUserException;8import org.slf4j.Logger;9import org.slf4j.LoggerFactory;10import java.lang.annotation.Annotation;11import java.lang.reflect.AccessibleObject;12import java.lang.reflect.Constructor;13import java.lang.reflect.Field;14import java.lang.reflect.InvocationTargetException;15import java.lang.reflect.Method;16import java.lang.reflect.Modifier;17import java.util.Arrays;18import java.util.List;19import java.util.Optional;20import java.util.stream.Collectors;21import java.util.stream.StreamSupport;22import static java.lang.String.format;23public class ReflectionUtil {24 private static Logger log = LoggerFactory.getLogger( ReflectionUtil.class );25 /**26 * Iterates over all fields of the given class and all its super classes27 * and calls action.act() for the fields that are annotated with the given annotation.28 */29 public static void forEachField( final Object object, Class<?> clazz, final FieldPredicate predicate, final FieldAction action ){30 forEachSuperClass( clazz, clazzAction -> {31 for( Field field : clazzAction.getDeclaredFields() ) {32 if( predicate.isTrue( field ) ) {33 action.act( object, field );34 }35 }36 } );37 }38 /**39 * Iterates over all methods of the given class and all its super classes40 * and calls action.act() for the methods that are annotated with the given annotation.41 */42 public static void forEachMethod( final Object object, Class<?> clazz, final Class<? extends Annotation> annotation,43 final MethodAction action ){44 forEachSuperClass( clazz, clazzAction -> {45 for( Method method : clazzAction.getDeclaredMethods() ) {46 if( method.isAnnotationPresent( annotation ) ) {47 action.act( object, method );48 }49 }50 } );51 }52 /**53 * Iterates over all super classes of the given class (including the class itself)54 * and calls action.act() for these classes.55 */56 public static void forEachSuperClass( Class<?> clazz, ClassAction action ){57 try {58 action.act( clazz );59 Class<?> superclass = clazz.getSuperclass();60 if( superclass != null ) {61 forEachSuperClass( superclass, action );62 }63 } catch( Exception e ) {64 throw Throwables.propagate( e );65 }66 }67 public static FieldPredicate hasAtLeastOneAnnotation( final Class<? extends Annotation>... annotation ){68 return field -> {69 for( Class<? extends Annotation> clazz : annotation ) {70 if( field.isAnnotationPresent( clazz ) ) {71 return true;72 }73 }74 return false;75 };76 }77 public static FieldPredicate allFields(){78 return field -> true;79 }80 public static FieldPredicate nonStaticField(){81 return field -> !Modifier.isStatic( field.getModifiers() );82 }83 public static boolean hasConstructor( Class<?> type, Class<?>... parameterTypes ){84 try {85 type.getDeclaredConstructor( parameterTypes );86 return true;87 } catch( NoSuchMethodException e ) {88 return false;89 }90 }91 public interface FieldPredicate {92 boolean isTrue( Field field ) throws Exception;93 }94 public interface ClassAction {95 void act( Class<?> clazz ) throws Exception;96 }97 public interface FieldAction {98 void act( Object object, Field field ) throws Exception;99 }100 public interface MethodAction {101 void act( Object object, Method method ) throws Exception;102 }103 public static Optional<Method> findMethodTransitively( Class<?> clazz, String methodName ){104 if( clazz == null ) {105 return Optional.empty();106 }107 try {108 return Optional.of( clazz.getDeclaredMethod( methodName ) );109 } catch( NoSuchMethodException e ) {110 return findMethodTransitively( clazz.getSuperclass(), methodName );111 }112 }113 public static <T> T newInstance( Class<T> type ){114 return newInstance( type, new Class<?>[0] );115 }116 public static <T> T newInstance( Class<T> type, Class<?>[] parameterTypes, Object... parameterValues ){117 try {118 Constructor<T> constructor = type.getDeclaredConstructor( parameterTypes );119 constructor.setAccessible( true );120 return constructor.newInstance( parameterValues );121 } catch( InstantiationException e ) {122 throw new RuntimeException( e );123 } catch( IllegalAccessException e ) {124 throw new RuntimeException( e );125 } catch( NoSuchMethodException e ) {126 throw new RuntimeException( e );127 } catch( InvocationTargetException e ) {128 throw new RuntimeException( e );129 }130 }131 public static void invokeMethod( Object object, Method method, String errorDescription ){132 log.debug( "Executing method %s of class %s", method, object.getClass() );133 makeAccessible( method, errorDescription );134 try {135 method.invoke( object );136 } catch( IllegalArgumentException e ) {137 log.debug( "Caught exception:", e );138 throw new JGivenExecutionException( "Could not execute " + toReadableString( method ) + errorDescription +139 ", because it requires parameters. " + "Remove the parameters and try again.", e );140 } catch( IllegalAccessException e ) {141 log.debug( "Caught exception:", e );142 throw new JGivenExecutionException( "Could not execute " + toReadableString( method ) + errorDescription +143 ", because of insuffient access rights. "144 + "Either make the method public or disable your security manager while executing JGiven tests.", e );145 } catch( InvocationTargetException e ) {146 throw new JGivenUserException( method, errorDescription, e.getCause() );147 }148 }149 /**150 * Returns a {@link List} of objects reflecting all the non-static field values declared by the class or interface151 * represented by the given {@link Class} object and defined by the given {@link Object}. This includes152 * {@code public}, {@code protected}, default (package) access, and {@code private} fields, but excludes inherited153 * fields. The elements in the {@link List} returned are not sorted and are not in any particular order. This method154 * returns an empty {@link List} if the class or interface declares no fields, or if the given {@link Class} object155 * represents a primitive type, an array class, or void.156 *157 * @param clazz class or interface declaring fields158 * @param target instance of given {@code clazz} from which field values should be retrieved159 * @param errorDescription customizable part of logged error message160 * @return a {@link List} containing all the found field values (never {@code null})...

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

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 method in JGivenUserException

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful