Best JGiven code snippet using com.tngtech.jgiven.impl.ScenarioExecutor.injectStages
Source:ScenarioExecutor.java
...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 }...
Source:ScenarioExecutorTest.java
...74 @Test75 public void steps_are_injected() {76 ScenarioExecutor executor = new ScenarioExecutor();77 TestClass testClass = new TestClass();78 executor.injectStages( testClass );79 assertThat( testClass.step ).isNotNull();80 assertThat( testClass.step.subStep ).isNotNull();81 }82 @Test83 public void recursive_steps_are_injected_correctly() {84 ScenarioExecutor executor = new ScenarioExecutor();85 RecursiveTestClass testClass = new RecursiveTestClass();86 executor.injectStages( testClass );87 assertThat( testClass.step ).isNotNull();88 assertThat( testClass.step.step ).isSameAs( testClass.step );89 }90 @Test91 public void BeforeStage_methods_may_not_have_parameters() {92 expectedExceptionRule.expect( JGivenExecutionException.class );93 expectedExceptionRule.expectMessage( "Could not execute method 'setup' of class 'BeforeStageWithParameters'" );94 expectedExceptionRule.expectMessage( ", because it requires parameters" );95 ScenarioExecutor executor = new ScenarioExecutor();96 BeforeStageWithParameters stage = executor.addStage( BeforeStageWithParameters.class );97 executor.startScenario( "Test" );98 stage.something();99 }100 @Test...
Source:MockScenarioExecutor.java
...46 ) {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}...
injectStages
Using AI Code Generation
1package com.tngtech.jgiven.example;2import com.tngtech.jgiven.Stage;3import com.tngtech.jgiven.annotation.ProvidedScenarioState;4import com.tngtech.jgiven.annotation.ScenarioState;5import com.tngtech.jgiven.annotation.Table;6import com.tngtech.jgiven.annotation.TableHeader;7import com.tngtech.jgiven.annotation.TableRow;8import com.tngtech.jgiven.config.AbstractJGivenConfiguration;9import com.tngtech.jgiven.config.JGivenConfiguration;10import com.tngtech.jgiven.impl.ScenarioExecutor;11import com.tngtech.jgiven.junit.SimpleScenarioTest;12import com.tngtech.jgiven.report.model.ExecutionStatus;13import com.tngtech.jgiven.report.model.ReportModel;14import com.tngtech.jgiven.report.model.ScenarioModel;15import com.tngtech.jgiven.report.model.StepModel;16import com.tngtech.jgiven.report.text.TextReportGenerator;17import org.junit.Test;18import java.util.ArrayList;19import java.util.List;20public class JGivenTest extends SimpleScenarioTest<GivenTest, WhenTest, ThenTest> {21 public void test() {22 List<Stage<?>> stages = new ArrayList<Stage<?>>();23 stages.add(new GivenTest().some_state());24 stages.add(new WhenTest().some_action());25 stages.add(new ThenTest().some_outcome());26 ScenarioExecutor scenarioExecutor = new ScenarioExecutor();27 scenarioExecutor.setConfiguration(new AbstractJGivenConfiguration() {28 public boolean isHtmlReportEnabled() {29 return false;30 }31 });32 scenarioExecutor.setScenarioClass(getClass());33 scenarioExecutor.setScenarioModel(new ScenarioModel());34 scenarioExecutor.injectStages(stages);35 ReportModel reportModel = new ReportModel();36 reportModel.addScenarioModel(scenarioExecutor.getScenarioModel());37 TextReportGenerator textReportGenerator = new TextReportGenerator();38 textReportGenerator.setConfiguration(new AbstractJGivenConfiguration() {39 public boolean isHtmlReportEnabled() {40 return false;41 }42 });43 textReportGenerator.setReportModel(reportModel);44 textReportGenerator.generateReport();45 }46}47package com.tngtech.jgiven.example;48import com.tngtech.jgiven.Stage;49import com.tngtech.jgiven.annotation.ProvidedScenarioState;50public class GivenTest extends Stage<GivenTest> {51 Object someState;
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!!