Best JGiven code snippet using com.tngtech.jgiven.exception.JGivenInjectionException
Source:ValueInjector.java
...5import com.tngtech.jgiven.annotation.ProvidedScenarioState;6import com.tngtech.jgiven.annotation.ScenarioState;7import com.tngtech.jgiven.annotation.ScenarioState.Resolution;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) {140 Object value = null;141 try {142 value = field.get(instance);143 } catch (IllegalAccessException e) {144 throw new JGivenInjectionException("The guaranteed field inside the scenario state cannot be accessed",145 e);146 }147 if (value == null) {148 throw new JGivenMissingGuaranteedScenarioStateException(field);149 }150 }151}...
Source:ReflectionUtilTest.java
...3import org.junit.Rule;4import org.junit.Test;5import org.junit.rules.ExpectedException;6import com.tngtech.jgiven.exception.JGivenExecutionException;7import com.tngtech.jgiven.exception.JGivenInjectionException;8public class ReflectionUtilTest {9 @Rule10 public final ExpectedException expectedException = ExpectedException.none();11 static class TestClass {12 private String testField;13 private void testMethod( Integer someArg ) {}14 }15 @Test16 public void injection_exception_is_thrown_if_field_cannot_be_set() throws Exception {17 expectedException.expect( JGivenInjectionException.class );18 ReflectionUtil.setField( TestClass.class.getDeclaredField( "testField" ), new TestClass(), 5, "test description" );19 }20 @Test21 public void makeAccessible_does_not_throw_execptions() throws Exception {22 AccessibleObject stub = new AccessibleObject() {23 @Override24 public void setAccessible( boolean flag ) throws SecurityException {25 throw new SecurityException();26 }27 };28 ReflectionUtil.makeAccessible( stub, "test" );29 }30 @Test31 public void execution_exception_is_thrown_if_method_cannot_be_invoked() throws Exception {...
Source:JGivenInjectionException.java
1package com.tngtech.jgiven.exception;2public class JGivenInjectionException extends RuntimeException {3 private static final long serialVersionUID = 1L;4 public JGivenInjectionException( String message, Exception e ) {5 super( message, e );6 }7}...
JGivenInjectionException
Using AI Code Generation
1import com.tngtech.jgiven.exception.JGivenInjectionException;2public class JGivenInjectionExceptionDemo {3 public static void main(String args[]) {4 JGivenInjectionException obj = new JGivenInjectionException("Exception");5 System.out.println("Exception: " + obj.getMessage());6 }7}
JGivenInjectionException
Using AI Code Generation
1import com.tngtech.jgiven.exception.JGivenInjectionException;2public class JGivenInjectionExceptionDemo {3 public static void main(String[] args) {4 JGivenInjectionException jGivenInjectionException = new JGivenInjectionException("JGivenInjectionException");5 System.out.println(jGivenInjectionException);6 }7}
JGivenInjectionException
Using AI Code Generation
1import com.tngtech.jgiven.exception.JGivenInjectionException;2public class JGivenInjectionExceptionDemo {3 public static void main(String[] args) {4 try {5 throw new JGivenInjectionException("An error occurred");6 } catch (JGivenInjectionException e) {7 System.out.println("JGivenInjectionException caught");8 }9 }10}
JGivenInjectionException
Using AI Code Generation
1import com.tngtech.jgiven.exception.JGivenInjectionException;2public class JGivenInjectionExceptionDemo {3 public static void main(String[] args) {4 try {5 throw new JGivenInjectionException("JGivenInjectionException is thrown");6 } catch (JGivenInjectionException e) {7 System.out.println(e);8 }9 }10}11 at JGivenInjectionExceptionDemo.main(1.java:8)
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!!