Best JGiven code snippet using com.tngtech.jgiven.impl.util.AssertionUtil
Source:MockScenarioModelBuilder.java
...15import com.tngtech.jgiven.exception.JGivenWrongUsageException;16import com.tngtech.jgiven.format.ObjectFormatter;17import com.tngtech.jgiven.impl.Config;18import com.tngtech.jgiven.impl.ScenarioModelBuilder;19import com.tngtech.jgiven.impl.util.AssertionUtil;20import com.tngtech.jgiven.impl.util.WordUtil;21import com.tngtech.jgiven.report.model.*;22import xyz.multicatch.mockgiven.core.annotations.as.AsProviderFactory;23import xyz.multicatch.mockgiven.core.annotations.caseas.CaseAsFactory;24import xyz.multicatch.mockgiven.core.annotations.caseas.CaseAsProviderFactory;25import xyz.multicatch.mockgiven.core.annotations.description.AnnotatedDescriptionFactory;26import xyz.multicatch.mockgiven.core.annotations.description.DescriptionData;27import xyz.multicatch.mockgiven.core.annotations.description.DescriptionQueue;28import xyz.multicatch.mockgiven.core.annotations.description.InlineWithNext;29import xyz.multicatch.mockgiven.core.annotations.tag.AnnotationTagExtractor;30import xyz.multicatch.mockgiven.core.annotations.tag.AnnotationTagUtils;31import xyz.multicatch.mockgiven.core.resources.TextResourceProvider;32import xyz.multicatch.mockgiven.core.scenario.cases.CaseDescription;33import xyz.multicatch.mockgiven.core.scenario.cases.CaseDescriptionFactory;34import xyz.multicatch.mockgiven.core.scenario.cases.ExtendedScenarioCaseModel;35import xyz.multicatch.mockgiven.core.scenario.methods.DescriptionFactory;36import xyz.multicatch.mockgiven.core.scenario.methods.arguments.ArgumentUtils;37import xyz.multicatch.mockgiven.core.scenario.methods.arguments.ParameterFormatterFactory;38import xyz.multicatch.mockgiven.core.scenario.methods.arguments.ParameterFormatterUtils;39import xyz.multicatch.mockgiven.core.scenario.state.CurrentScenarioState;40import xyz.multicatch.mockgiven.core.scenario.steps.ExtendedStepModel;41import xyz.multicatch.mockgiven.core.scenario.steps.StepCommentFactory;42import xyz.multicatch.mockgiven.core.scenario.steps.StepModelFactory;43import xyz.multicatch.mockgiven.core.utils.ExceptionUtils;44public class MockScenarioModelBuilder extends ScenarioModelBuilder {45 private static final Set<String> STACK_TRACE_FILTER = ImmutableSet46 .of("sun.reflect", "com.tngtech.jgiven.impl.intercept", "com.tngtech.jgiven.impl.intercept", "$$EnhancerByCGLIB$$",47 "java.lang.reflect", "net.sf.cglib.proxy", "com.sun.proxy");48 private static final boolean FILTER_STACK_TRACE = Config.config()49 .filterStackTrace();50 private final Stack<ExtendedStepModel> parentSteps = new Stack<>();51 private final CurrentScenarioState currentScenarioState;52 private final StepCommentFactory stepCommentFactory;53 private final DescriptionFactory descriptionFactory;54 private final CaseDescriptionFactory caseDescriptionFactory;55 private final DescriptionQueue descriptionQueue;56 private AbstractJGivenConfiguration configuration;57 private StepModelFactory stepModelFactory;58 private AnnotationTagExtractor annotationTagExtractor;59 private ParameterFormatterFactory formatterFactory;60 private ExtendedScenarioModel scenarioModel;61 private ExtendedScenarioCaseModel scenarioCaseModel;62 private ExtendedStepModel currentStep;63 private Word introWord;64 private long scenarioStartedNanos;65 private ReportModel reportModel;66 public MockScenarioModelBuilder(CurrentScenarioState currentScenarioState, TextResourceProvider textResourceProvider) {67 this.currentScenarioState = currentScenarioState;68 this.stepCommentFactory = new StepCommentFactory();69 this.descriptionFactory = new DescriptionFactory(new AsProviderFactory(), new AnnotatedDescriptionFactory(), textResourceProvider);70 this.caseDescriptionFactory = new CaseDescriptionFactory(new CaseAsFactory(), new CaseAsProviderFactory());71 this.descriptionQueue = new DescriptionQueue();72 this.configuration = new DefaultConfiguration();73 initializeDependentOnConfiguration();74 }75 public MockScenarioModelBuilder(76 CurrentScenarioState currentScenarioState,77 StepCommentFactory stepCommentFactory,78 DescriptionFactory descriptionFactory,79 CaseDescriptionFactory caseDescriptionFactory,80 DescriptionQueue descriptionQueue81 ) {82 this.currentScenarioState = currentScenarioState;83 this.stepCommentFactory = stepCommentFactory;84 this.descriptionFactory = descriptionFactory;85 this.caseDescriptionFactory = caseDescriptionFactory;86 this.descriptionQueue = descriptionQueue;87 this.configuration = new DefaultConfiguration();88 initializeDependentOnConfiguration();89 }90 private void initializeDependentOnConfiguration() {91 formatterFactory = new ParameterFormatterFactory(configuration);92 stepModelFactory = new StepModelFactory(currentScenarioState, formatterFactory, descriptionFactory);93 annotationTagExtractor = AnnotationTagExtractor.forConfig(configuration);94 }95 @Override96 public void scenarioStarted(String description) {97 scenarioStartedNanos = System.nanoTime();98 String readableDescription = description;99 if (description.contains("_")) {100 readableDescription = description.replace('_', ' ');101 } else if (!description.contains(" ")) {102 readableDescription = WordUtil.camelCaseToCapitalizedReadableText(description);103 }104 scenarioCaseModel = new ExtendedScenarioCaseModel();105 scenarioModel = new ExtendedScenarioModel();106 scenarioModel.addCase(scenarioCaseModel);107 scenarioModel.setDescription(readableDescription);108 }109 @Override110 public void addStepMethod(111 Method paramMethod,112 List<NamedArgument> arguments,113 InvocationMode mode,114 boolean hasNestedSteps115 ) {116 ExtendedStepModel stepModel = stepModelFactory.create(paramMethod, arguments, mode, introWord);117 DescriptionData description = DescriptionData.of(stepModel);118 descriptionQueue.add(description);119 if (introWord != null) {120 introWord = null;121 }122 if (!paramMethod.isAnnotationPresent(InlineWithNext.class)) {123 stepModel.setDescription(descriptionQueue.join());124 if (parentSteps.empty()) {125 getCurrentScenarioCase().addStep(stepModel);126 } else {127 parentSteps.peek()128 .addNestedStep(stepModel);129 }130 if (hasNestedSteps) {131 parentSteps.push(stepModel);132 }133 currentStep = stepModel;134 }135 }136 @Override137 public void introWordAdded(String value) {138 introWord = new Word();139 introWord.setIntroWord(true);140 introWord.setValue(value);141 }142 @Override143 public void stepCommentAdded(List<NamedArgument> arguments) {144 if (currentStep == null) {145 throw new JGivenWrongUsageException("A step comment must be added after the corresponding step, "146 + "but no step has been executed yet.");147 }148 currentStep.setComment(stepCommentFactory.create(arguments));149 }150 private ScenarioCaseModel getCurrentScenarioCase() {151 if (scenarioCaseModel == null) {152 scenarioStarted("A Scenario");153 }154 return scenarioCaseModel;155 }156 @Override157 public void stepMethodInvoked(158 Method method,159 List<NamedArgument> arguments,160 InvocationMode mode,161 boolean hasNestedSteps162 ) {163 if (method.isAnnotationPresent(IntroWord.class)) {164 introWordAdded(descriptionFactory.create(currentScenarioState.getCurrentStage(), method));165 } else if (method.isAnnotationPresent(StepComment.class)) {166 stepCommentAdded(arguments);167 } else {168 addTags(method.getAnnotations());169 addTags(method.getDeclaringClass()170 .getAnnotations());171 addStepMethod(method, arguments, mode, hasNestedSteps);172 }173 }174 @Override175 public void stepMethodFailed(Throwable t) {176 if (currentStep != null) {177 currentStep.setStatus(StepStatus.FAILED);178 }179 }180 @Override181 public void stepMethodFinished(182 long durationInNanos,183 boolean hasNestedSteps184 ) {185 if (hasNestedSteps && !parentSteps.isEmpty()) {186 currentStep = parentSteps.peek();187 }188 if (currentStep != null) {189 currentStep.setDurationInNanos(durationInNanos);190 if (hasNestedSteps) {191 if (currentStep.getStatus() != StepStatus.FAILED) {192 currentStep.inheritStatusFromNested();193 }194 parentSteps.pop();195 }196 }197 if (!hasNestedSteps && !parentSteps.isEmpty()) {198 currentStep = parentSteps.peek();199 }200 }201 @Override202 public void scenarioFailed(Throwable e) {203 scenarioCaseModel.setException(e, getStackTrace(e));204 }205 private List<String> getStackTrace(Throwable throwable) {206 if (FILTER_STACK_TRACE) {207 return ExceptionUtils.getFilteredStackTrace(throwable, STACK_TRACE_FILTER);208 } else {209 return ExceptionUtils.getStackTrace(throwable);210 }211 }212 @Override213 public void scenarioStarted(214 Class<?> testClass,215 Method method,216 List<NamedArgument> namedArguments217 ) {218 readConfiguration(testClass);219 readAnnotations(testClass, method);220 scenarioModel.setClassName(testClass.getName());221 scenarioModel.setExplicitParametersWithoutUnderline(ArgumentUtils.getNames(namedArguments));222 scenarioModel.setTestMethodName(method.getName());223 List<ObjectFormatter<?>> formatter = formatterFactory.create(method.getParameters(), namedArguments);224 List<String> arguments = ParameterFormatterUtils.toStringList(formatter, ArgumentUtils.getValues(namedArguments));225 scenarioCaseModel.setExplicitArguments(arguments);226 setCaseDescription(testClass, method, namedArguments);227 }228 private void readConfiguration(Class<?> testClass) {229 configuration = ConfigurationUtil.getConfiguration(testClass);230 initializeDependentOnConfiguration();231 }232 private void readAnnotations(233 Class<?> testClass,234 Method method235 ) {236 String scenarioDescription = descriptionFactory.create(currentScenarioState.getCurrentStage(), method);237 scenarioStarted(scenarioDescription);238 if (method.isAnnotationPresent(ExtendedDescription.class)) {239 scenarioModel.setExtendedDescription(method.getAnnotation(ExtendedDescription.class)240 .value());241 }242 if (method.isAnnotationPresent(NotImplementedYet.class) || method.isAnnotationPresent(Pending.class)) {243 scenarioCaseModel.setStatus(ExecutionStatus.SCENARIO_PENDING);244 }245 if (scenarioCaseModel.isFirstCase()) {246 addTags(testClass.getAnnotations());247 addTags(method.getAnnotations());248 }249 }250 private void setCaseDescription(251 Class<?> testClass,252 Method method,253 List<NamedArgument> namedArguments254 ) {255 CaseDescription caseDescription = caseDescriptionFactory.create(method, testClass, scenarioCaseModel, namedArguments);256 if (caseDescription != null) {257 String description = caseDescriptionFactory.create(caseDescription, scenarioCaseModel.getExplicitArguments());258 scenarioCaseModel.setDescription(description);259 }260 }261 public void addTags(Annotation... annotations) {262 for (Annotation annotation : annotations) {263 addTags(annotationTagExtractor.extract(annotation));264 }265 }266 private void addTags(List<Tag> tags) {267 if (!tags.isEmpty()) {268 if (reportModel != null) {269 this.reportModel.addTags(tags);270 }271 if (scenarioModel != null) {272 this.scenarioModel.addTags(tags);273 }274 }275 }276 @Override277 public void scenarioFinished() {278 AssertionUtil.assertTrue(scenarioStartedNanos > 0, "Scenario has no start time");279 long durationInNanos = System.nanoTime() - scenarioStartedNanos;280 scenarioCaseModel.setDurationInNanos(durationInNanos);281 scenarioModel.addDurationInNanos(durationInNanos);282 reportModel.addScenarioModelOrMergeWithExistingOne(scenarioModel);283 }284 @Override285 public void attachmentAdded(Attachment attachment) {286 currentStep.setAttachment(attachment);287 }288 @Override289 public void extendedDescriptionUpdated(String extendedDescription) {290 currentStep.setExtendedDescription(extendedDescription);291 }292 @Override...
Source:ReportModel.java
...6import com.tngtech.jgiven.annotation.As;7import com.tngtech.jgiven.annotation.AsProvider;8import com.tngtech.jgiven.annotation.Description;9import com.tngtech.jgiven.impl.params.DefaultAsProvider;10import com.tngtech.jgiven.impl.util.AssertionUtil;11import com.tngtech.jgiven.impl.util.ReflectionUtil;12import java.util.Comparator;13import java.util.EnumSet;14import java.util.List;15import java.util.Map;16import java.util.Optional;17public class ReportModel {18 /**19 * Full qualified name of the test class.20 */21 private String className;22 /**23 * An optional name to group scenarios24 */25 private String name;26 /**27 * An optional description of the test class.28 */29 private String description;30 private List<ScenarioModel> scenarios = Lists.newArrayList();31 private Map<String, Tag> tagMap = Maps.newLinkedHashMap();32 public void accept(ReportModelVisitor visitor) {33 visitor.visit(this);34 List<ScenarioModel> sorted = sortByDescription();35 for (ScenarioModel m : sorted) {36 m.accept(visitor);37 }38 visitor.visitEnd(this);39 }40 private List<ScenarioModel> sortByDescription() {41 List<ScenarioModel> sorted = Lists.newArrayList(getScenarios());42 sorted.sort(Comparator.comparing(self -> self.getDescription().toLowerCase()));43 return sorted;44 }45 public ScenarioModel getLastScenarioModel() {46 return getScenarios().get(getScenarios().size() - 1);47 }48 public Optional<ScenarioModel> findScenarioModel(String scenarioDescription) {49 for (ScenarioModel model : getScenarios()) {50 if (model.getDescription().equals(scenarioDescription)) {51 return Optional.of(model);52 }53 }54 return Optional.empty();55 }56 public StepModel getFirstStepModelOfLastScenario() {57 return getLastScenarioModel().getCase(0).getStep(0);58 }59 public synchronized void addScenarioModel(ScenarioModel currentScenarioModel) {60 scenarios.add(copyModelToKeepOriginalIsolatedInItsThread(currentScenarioModel));61 }62 private ScenarioModel copyModelToKeepOriginalIsolatedInItsThread(ScenarioModel currentScenarioModel) {63 return new ScenarioModel(currentScenarioModel);64 }65 public String getSimpleClassName() {66 return Iterables.getLast(Splitter.on('.').split(getClassName()));67 }68 public String getDescription() {69 return description;70 }71 public void setDescription(String description) {72 this.description = description;73 }74 public String getClassName() {75 return className;76 }77 public void setClassName(String className) {78 this.className = className;79 }80 public List<ScenarioModel> getScenarios() {81 return scenarios;82 }83 public void setScenarios(List<ScenarioModel> scenarios) {84 this.scenarios = scenarios;85 }86 public String getPackageName() {87 int index = this.className.lastIndexOf('.');88 if (index == -1) {89 return "";90 }91 return this.className.substring(0, index);92 }93 public List<ScenarioModel> getFailedScenarios() {94 return getScenariosWithStatus(ExecutionStatus.FAILED);95 }96 public List<ScenarioModel> getPendingScenarios() {97 return getScenariosWithStatus(ExecutionStatus.SCENARIO_PENDING, ExecutionStatus.SOME_STEPS_PENDING);98 }99 public List<ScenarioModel> getScenariosWithStatus(ExecutionStatus first, ExecutionStatus... rest) {100 EnumSet<ExecutionStatus> stati = EnumSet.of(first, rest);101 List<ScenarioModel> result = Lists.newArrayList();102 for (ScenarioModel m : scenarios) {103 ExecutionStatus executionStatus = m.getExecutionStatus();104 if (stati.contains(executionStatus)) {105 result.add(m);106 }107 }108 return result;109 }110 public synchronized void addTag(Tag tag) {111 this.tagMap.put(tag.toIdString(), tag);112 }113 public synchronized void addTags(Iterable<Tag> tags) {114 tags.forEach(this::addTag);115 }116 public synchronized Tag getTagWithId(String tagId) {117 Tag tag = this.tagMap.get(tagId);118 AssertionUtil.assertNotNull(tag, "Could not find tag with id " + tagId);119 return tag;120 }121 public synchronized Map<String, Tag> getTagMap() {122 return tagMap;123 }124 public synchronized void setTagMap(Map<String, Tag> tagMap) {125 this.tagMap = tagMap;126 }127 public synchronized void addScenarioModelOrMergeWithExistingOne(ScenarioModel scenarioModel) {128 Optional<ScenarioModel> existingScenarioModel = findScenarioModel(scenarioModel.getDescription());129 if (existingScenarioModel.isPresent()) {130 AssertionUtil.assertTrue(scenarioModel.getScenarioCases().size() == 1,131 "ScenarioModel has more than one case");132 existingScenarioModel.get().addCase(scenarioModel.getCase(0));133 existingScenarioModel.get().addDurationInNanos(scenarioModel.getDurationInNanos());134 } else {135 addScenarioModel(scenarioModel);136 }137 }138 public synchronized void setTestClass(Class<?> testClass) {139 AssertionUtil.assertTrue(className == null || testClass.getName().equals(className),140 "Test class of the same report model was set to different values. 1st value: " + className141 + ", 2nd value: " + testClass.getName());142 setClassName(testClass.getName());143 if (testClass.isAnnotationPresent(Description.class)) {144 setDescription(testClass.getAnnotation(Description.class).value());145 }146 As as = testClass.getAnnotation(As.class);147 AsProvider provider = as != null148 ? ReflectionUtil.newInstance(as.provider())149 : new DefaultAsProvider();150 name = provider.as(as, testClass);151 }152 public String getName() {153 return name;...
Source:ScenarioTestListener.java
...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 }...
AssertionUtil
Using AI Code Generation
1import com.tngtech.jgiven.impl.util.AssertionUtil;2public class AssertionUtilTest {3 public static void main(String[] args) {4 AssertionUtil.assertTrue(1 == 1, "1 is not equal to 1");5 }6}7at com.tngtech.jgiven.impl.util.AssertionUtil.assertTrue(AssertionUtil.java:24)8at com.tngtech.jgiven.impl.util.AssertionUtilTest.main(AssertionUtilTest.java:7)
AssertionUtil
Using AI Code Generation
1import com.tngtech.jgiven.impl.util.AssertionUtil;2import com.tngtech.jgiven.impl.util.AssertionUtil$;3public class AssertionUtilTest {4 public static void main(String[] args) {5 AssertionUtil$.MODULE$.assertThat(true).isTrue();6 }7}
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!!