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

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

Source:ScenarioExecutor.java Github

copy

Full Screen

...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");...

Full Screen

Full Screen

Source:ScenarioTestListener.java Github

copy

Full Screen

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...

Full Screen

Full Screen

Source:FailIfPassedException.java Github

copy

Full Screen

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}...

Full Screen

Full Screen

FailIfPassedException

Using AI Code Generation

copy

Full Screen

1package com.tngtech.jgiven.examples;2import org.junit.Test;3import org.junit.runner.RunWith;4import com.tngtech.jgiven.Stage;5import com.tngtech.jgiven.annotation.ProvidedScenarioState;6import com.tngtech.jgiven.annotation.ScenarioState;7import com.tngtech.jgiven.annotation.ScenarioState.Resolution;8import com.tngtech.jgiven.junit.ScenarioTest;9@RunWith( ScenarioTest.class )10public class FailIfPassedExceptionTest extends Stage<FailIfPassedExceptionTest> {11 public void when_a_test_fails_then_jgiven_should_fail() {12 given().a_test_that_fails();13 }14 public void when_a_test_passes_then_jgiven_should_fail() {15 given().a_test_that_passes();16 }17 public void a_test_that_fails() {18 throw new AssertionError( "This test failed" );19 }20 public void a_test_that_passes() {21 }22}23package com.tngtech.jgiven.examples;24import org.junit.Test;25import org.junit.runner.RunWith;26import com.tngtech.jgiven.Stage;27import com.tngtech.jgiven.annotation.ScenarioState;28import com.tngtech.jgiven.annotation.ScenarioState.Resolution;29import com.tngtech.jgiven.annotation.ScenarioStateRule;30import com.tngtech.jgiven.junit.ScenarioTest;31@RunWith( ScenarioTest.class )32public class ScenarioStateRuleTest extends Stage<ScenarioStateRuleTest> {33 String name;34 @ScenarioState( resolution = Resolution.NAME )35 String name2;36 @ScenarioState( resolution = Resolution.NAME )37 String name3;38 public void scenario_state_can_be_resolved_by_name() {39 given().a_scenario_state_with_name_$name( "foo" )40 .and().another_scenario_state_

Full Screen

Full Screen

FailIfPassedException

Using AI Code Generation

copy

Full Screen

1import com.tngtech.jgiven.exception.FailIfPassedException;2import com.tngtech.jgiven.exception.JGivenMissingMethodException;3import com.tngtech.jgiven.exception.JGivenMissingScenarioException;4import com.tngtech.jgiven.exception.JGivenMissingStageException;5import com.tngtech.jgiven.exception.JGivenMissingTestException;6import com.tngtech.jgiven.exception.MultipleFailuresException;7import com.tngtech.jgiven.exception.ScenarioTestFailureException;8import com.tngtech.jgiven.exception.ScenarioTestIncompleteException;9import com.tngtech.jgiven.exception.ScenarioTestPendingException;10import com.tngtech.jgiven.exception.ScenarioTestSkippedException;11import com.tngtech.jgiven.exception.ScenarioTestUndefinedException;12import com.tngtech.jgiven.exception.ScenarioTestUndefinedStepException;13import com.tngtech.jgiven.exception.ScenarioTestUnfinishedExce

Full Screen

Full Screen

FailIfPassedException

Using AI Code Generation

copy

Full Screen

1package com.tngtech.jgiven.exception;2import org.junit.Test;3public class FailIfPassedExceptionTest {4@Test(expected = FailIfPassedException.class)5public void testFailIfPassedException() {6 throw new FailIfPassedException("FailIfPassedException");7}8}9 at org.junit.Assert.fail(Assert.java:86)10 at org.junit.Assert.assertTrue(Assert.java:41)11 at org.junit.Assert.assertTrue(Assert.java:52)12 at com.tngtech.jgiven.exception.FailIfPassedExceptionTest.testFailIfPassedException(FailIfPassedExceptionTest.java:13)

Full Screen

Full Screen

FailIfPassedException

Using AI Code Generation

copy

Full Screen

1import com.tngtech.jgiven.exception.FailIfPassedException;2import org.testng.annotations.Test;3public class FailIfPassedExceptionExample {4@Test(expectedExceptions = FailIfPassedException.class)5public void testFailIfPassedException() {6throw new FailIfPassedException();7}8}9at org.testng.Assert.fail(Assert.java:94)10at org.testng.Assert.failNotEquals(Assert.java:494)11at org.testng.Assert.assertEquals(Assert.java:123)12at org.testng.Assert.assertEquals(Assert.java:176)13at org.testng.Assert.assertEquals(Assert.java:186)14at com.tngtech.jgiven.testng.JGivenTestListener.onTestFailure(JGivenTestListener.java:231)15at org.testng.internal.Invoker.runTestListeners(Invoker.java:1893)16at org.testng.internal.Invoker.runTestListeners(Invoker.java:1885)17at org.testng.internal.Invoker.invokeMethod(Invoker.java:657)18at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:853)19at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1167)20at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)21at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)22at org.testng.TestRunner.privateRun(TestRunner.java:756)23at org.testng.TestRunner.run(TestRunner.java:610)24at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)25at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)26at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)27at org.testng.SuiteRunner.run(SuiteRunner.java:289)28at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)29at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)30at org.testng.TestNG.runSuitesSequentially(TestNG.java:1284)31at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)32at org.testng.TestNG.runSuites(TestNG.java:1124)33at org.testng.TestNG.run(TestNG.java:1096)34at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)35at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)

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 FailIfPassedException

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful