Best JGiven code snippet using com.tngtech.jgiven.exception.FailIfPassedException
Source:ScenarioExecutor.java  
...8import com.tngtech.jgiven.annotation.Pending;9import com.tngtech.jgiven.annotation.ScenarioRule;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);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");...Source:ScenarioTestListener.java  
1package com.tngtech.jgiven.testng;2import static java.util.Arrays.asList;3import com.tngtech.jgiven.base.ScenarioTestBase;4import com.tngtech.jgiven.exception.FailIfPassedException;5import com.tngtech.jgiven.impl.ScenarioBase;6import com.tngtech.jgiven.impl.ScenarioHolder;7import com.tngtech.jgiven.impl.util.AssertionUtil;8import com.tngtech.jgiven.impl.util.ParameterNameUtil;9import com.tngtech.jgiven.report.impl.CommonReportHelper;10import com.tngtech.jgiven.report.model.NamedArgument;11import com.tngtech.jgiven.report.model.ReportModel;12import java.lang.reflect.Method;13import java.util.List;14import java.util.concurrent.ConcurrentHashMap;15import org.testng.ITestContext;16import org.testng.ITestListener;17import org.testng.ITestResult;18/**19 * TestNG Test listener to enable JGiven for a test class.20 */21@SuppressWarnings("checkstyle:AbbreviationAsWordInName")22public class ScenarioTestListener implements ITestListener {23    public static final String SCENARIO_ATTRIBUTE = "jgiven::scenario";24    public static final String REPORT_MODELS_ATTRIBUTE = "jgiven::reportModels";25    @Override26    public void onTestStart(ITestResult paramITestResult) {27        Object instance = paramITestResult.getInstance();28        ScenarioBase scenario;29        if (instance instanceof ScenarioTestBase<?, ?, ?>) {30            ScenarioTestBase<?, ?, ?> testInstance = (ScenarioTestBase<?, ?, ?>) instance;31            scenario = testInstance.createNewScenario();32        } else {33            scenario = new ScenarioBase();34        }35        ScenarioHolder.get().setScenarioOfCurrentThread(scenario);36        paramITestResult.setAttribute(SCENARIO_ATTRIBUTE, scenario);37        ReportModel reportModel = getReportModel(paramITestResult, instance.getClass());38        scenario.setModel(reportModel);39        //TestNG cannot run in parallel if stages are to be injected, because then multiple scenarios40        //will attempt to inject into a single test instance at the same time.41        new IncompatibleMultithreadingChecker().checkIncompatibleMultiThreading(paramITestResult);42        // TestNG does not work well when catching step exceptions, so we have to disable that feature43        // this mainly means that steps following a failing step are not reported in JGiven44        scenario.getExecutor().setSuppressStepExceptions(false);45        // avoid rethrowing exceptions as they are already thrown by the steps46        scenario.getExecutor().setSuppressExceptions(true);47        scenario.getExecutor().injectStages(instance);48        Method method = paramITestResult.getMethod().getConstructorOrMethod().getMethod();49        scenario.startScenario(instance.getClass(), method, getArgumentsFrom(method, paramITestResult));50        // inject state from the test itself51        scenario.getExecutor().readScenarioState(instance);52    }53    private ScenarioBase getScenario(ITestResult paramITestResult) {54        return (ScenarioBase) paramITestResult.getAttribute(SCENARIO_ATTRIBUTE);55    }56    private ReportModel getReportModel(ITestResult testResult, Class<?> clazz) {57        ConcurrentHashMap<String, ReportModel> reportModels = getReportModels(testResult.getTestContext());58        ReportModel model = reportModels.get(clazz.getName());59        if (model == null) {60            model = new ReportModel();61            model.setTestClass(clazz);62            ReportModel previousModel = reportModels.putIfAbsent(clazz.getName(), model);63            if (previousModel != null) {64                model = previousModel;65            }66        }67        AssertionUtil.assertNotNull(model, "Report model is null");68        return model;69    }70    @Override71    public void onTestSuccess(ITestResult paramITestResult) {72        testFinished(paramITestResult);73    }74    @Override75    public void onTestFailure(ITestResult paramITestResult) {76        ScenarioBase scenario = getScenario(paramITestResult);77        if (scenario != null) {78            scenario.getExecutor().failed(paramITestResult.getThrowable());79            testFinished(paramITestResult);80        }81    }82    @Override83    public void onTestSkipped(ITestResult testResult) {84    }85    private void testFinished(ITestResult testResult) {86        try {87            ScenarioBase scenario = getScenario(testResult);88            scenario.finished();89        } catch (FailIfPassedException ex) {90            testResult.setStatus(ITestResult.FAILURE);91            testResult.setThrowable(ex);92            testResult.getTestContext().getPassedTests().removeResult(testResult);93            testResult.getTestContext().getFailedTests().addResult(testResult);94        } catch (Throwable throwable) {95            throw new RuntimeException(throwable);96        } finally {97            ScenarioHolder.get().removeScenarioOfCurrentThread();98        }99    }100    @Override101    public void onTestFailedButWithinSuccessPercentage(ITestResult paramITestResult) {102    }103    @Override...Source:FailIfPassedException.java  
1package com.tngtech.jgiven.exception;2/**3 * @see com.tngtech.jgiven.annotation.Pending4 */5public class FailIfPassedException extends RuntimeException {6    private static final long serialVersionUID = 1L;7    public FailIfPassedException() {8        super( "Test succeeded, but failIfPassed set to true. Now might be the right time to remove the @Pending annotation." );9    }10}...FailIfPassedException
Using AI Code Generation
1import com.tngtech.jgiven.annotation.*;2import com.tngtech.jgiven.junit.ScenarioTest;3import com.tngtech.jgiven.report.model.StageStatus;4import com.tngtech.jgiven.report.model.StepStatus;5import com.tngtech.jgiven.testframework.TestFrameworkProvider;6import com.tngtech.jgiven.testframework.TestFrameworkProvider.TestResult;7import com.tngtech.jgiven.testframework.TestFrameworkProvider.TestResult.TestResultStatus;8import org.junit.Test;9import java.util.ArrayList;10import java.util.Arrays;11import java.util.List;12import static org.assertj.core.api.Assertions.assertThat;13public class FailIfPassedExceptionTest extends ScenarioTest<FailIfPassedExceptionTest.TestStage> {14    public void test_fail_if_passed_exception() {15        given().a_scenario_with_$_steps(2)16                .and().a_scenario_with_$_steps(1)17                .and().a_scenario_with_$_steps(3)18                .when().the_scenarios_are_executed()19                .then().the_test_should_fail_with_$_scenarios(2);20    }21    public static class TestStage extends Stage<TestStage> {22        private List<TestResult> testResults = new ArrayList<>();23        public TestStage a_scenario_with_$_steps(int numberOfSteps) {24            TestResult testResult = TestFrameworkProvider.getTestResult();25            testResult.setStatus(TestResultStatus.PASSED);26            for (int i = 0; i < numberOfSteps; i++) {27                testResult.addStepResult(StepStatus.PASSED, "step" + i, "");28            }29            testResults.add(testResult);30            return self();31        }32        public TestStage the_scenarios_are_executed() {33            for (TestResult testResult : testResults) {34                testResult.execute();35            }36            return self();37        }38        public TestStage the_test_should_fail_with_$_scenarios(int numberOfScenarios) {39            assertThat(testResults.stream().filter(TestResult::isFailed).count()).isEqualTo(numberOfScenarios);40            return self();41        }42    }43}44import com.tngtech.jgiven.annotation.*;45import com.tngtech.jgiven.junit.ScenarioTest;46import com.tngtech.jgiven.report.model.StageStatus;47import com.tngtech.jgiven.report.model.StepStatus;48import com.tngtech.jgiven.testframework.TestFrameworkFailIfPassedException
Using AI Code Generation
1import com.tngtech.jgiven.exception.FailIfPassedException;2import com.tngtech.jgiven.junit.ScenarioTest;3import org.junit.Test;4import static org.hamcrest.Matchers.is;5import static org.junit.Assert.assertThat;6public class Test1 extends ScenarioTest<GivenTest1, WhenTest1, ThenTest1> {7    public void test1() {8        given().something();9        when().something_else();10        then().something_else().something_else();11        throw new FailIfPassedException();12    }13}14import com.tngtech.jgiven.exception.FailIfPassedException;15import com.tngtech.jgiven.junit.ScenarioTest;16import org.junit.Test;17import static org.hamcrest.Matchers.is;18import static org.junit.Assert.assertThat;19public class Test2 extends ScenarioTest<GivenTest2, WhenTest2, ThenTest2> {20    public void test2() {21        given().something();22        when().something_else();23        then().something_else().something_else();24        throw new FailIfPassedException();25    }26}27import com.tngtech.jgiven.exception.FailIfPassedException;28import com.tngtech.jgiven.junit.ScenarioTest;29import org.junit.Test;30import static org.hamcrest.Matchers.is;31import static org.junit.Assert.assertThat;32public class Test3 extends ScenarioTest<GivenTest3, WhenTest3, ThenTest3> {33    public void test3() {34        given().something();35        when().something_else();36        then().something_else().something_else();37        throw new FailIfPassedException();38    }39}40import com.tngtech.jgiven.exception.FailIfPassedException;41import com.tngtech.jgiven.junit.ScenarioTest;42import org.junit.Test;43import static org.hamcrest.Matchers.is;44import static org.junit.Assert.assertThat;45public class Test4 extends ScenarioTest<GivenTest4, WhenTest4, ThenTest4> {46    public void test4() {47        given().something();48        when().something_else();49        then().something_else().something_else();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!!
