How to use getStepListener method of net.serenitybdd.junit.runners.SerenityRunner class

Best Serenity JUnit code snippet using net.serenitybdd.junit.runners.SerenityRunner.getStepListener

Source:SerenityRunner.java Github

copy

Full Screen

...255 private boolean dataDrivenTest() {256 return this instanceof TestClassRunnerForParameters;257 }258 private void dropListeners(final RunNotifier notifier) {259 JUnitStepListener listener = getStepListener();260 notifier.removeListener(listener);261 getStepListener().dropListeners();262 }263 protected void generateReports() {264 generateReportsFor(getTestOutcomes());265 }266 private boolean skipThisTest() {267 return testNotInCurrentBatch();268 }269 private boolean testNotInCurrentBatch() {270 return (batchManager != null) && (!batchManager.shouldExecuteThisTest(getDescription().testCount()));271 }272 /**273 * The Step Listener observes and records what happens during the execution of the test.274 * Once the test is over, the Step Listener can provide the acceptance test outcome in the275 * form of an TestOutcome object.276 * @return the current step listener277 */278 protected JUnitStepListener getStepListener() {279 if (stepListener == null) {280 buildAndConfigureListeners();281 }282 return stepListener;283 }284 protected void setStepListener(JUnitStepListener stepListener) {285 this.stepListener = stepListener;286 }287 private void buildAndConfigureListeners() {288 initStepEventBus();289 if (webtestsAreSupported()) {290 ThucydidesWebDriverSupport.initialize(requestedDriver);291 WebDriver driver = ThucydidesWebDriverSupport.getWebdriverManager().getWebdriver();292 initPagesObjectUsing(driver);293 setStepListener(initListenersUsing(getPages()));294 initStepFactoryUsing(getPages());295 } else {296 setStepListener(initListeners());297 initStepFactory();298 }299 }300 private RunNotifier initializeRunNotifier(RunNotifier notifier) {301 notifier.addListener(getStepListener());302 return notifier;303 }304 private int maxRetries() {305 return TEST_RETRY_COUNT.integerFrom(configuration.getEnvironmentVariables(), 0);306 }307 protected void initStepEventBus() {308 StepEventBus.getEventBus().clear();309 }310 private void initPagesObjectUsing(final WebDriver driver) {311 pages = new Pages(driver, getConfiguration());312 dependencyInjector = new PageObjectDependencyInjector(pages);313 }314 protected JUnitStepListener initListenersUsing(final Pages pageFactory) {315 return JUnitStepListener.withOutputDirectory(getConfiguration().getOutputDirectory())316 .and().withPageFactory(pageFactory)317 .and().withTestClass(getTestClass().getJavaClass())318 .and().build();319 }320 protected JUnitStepListener initListeners() {321 return JUnitStepListener.withOutputDirectory(getConfiguration().getOutputDirectory())322 .and().withTestClass(getTestClass().getJavaClass())323 .and().build();324 }325 private boolean webtestsAreSupported() {326 return TestCaseAnnotations.supportsWebTests(this.getTestClass().getJavaClass());327 }328 private void initStepFactoryUsing(final Pages pagesObject) {329 stepFactory = StepFactory.getFactory().usingPages(pagesObject);330 }331 private void initStepFactory() {332 stepFactory = StepFactory.getFactory();333 }334 private ReportService getReportService() {335 if (reportService == null) {336 reportService = new ReportService(getOutputDirectory(), getDefaultReporters());337 }338 return reportService;339 }340 /**341 * A test runner can generate reports via Reporter instances that subscribe342 * to the test runner. The test runner tells the reporter what directory to343 * place the reports in. Then, at the end of the test, the test runner344 * notifies these reporters of the test outcomes. The reporter's job is to345 * process each test run outcome and do whatever is appropriate.346 *347 * @param testOutcomeResults the test results from the previous test run.348 */349 private void generateReportsFor(final List<TestOutcome> testOutcomeResults) {350 getReportService().generateReportsFor(testOutcomeResults);351 getReportService().generateConfigurationsReport();352 }353 @Override354 protected void runChild(FrameworkMethod method, RunNotifier notifier) {355 TestMethodConfiguration theMethod = TestMethodConfiguration.forMethod(method);356 clearMetadataIfRequired();357 resetStepLibrariesIfRequired();358 if(!failureRerunner.hasToRunTest(method.getDeclaringClass().getCanonicalName(),method.getMethod().getName()))359 {360 return;361 }362 if (shouldSkipTest(method)) {363 return;364 }365 if (theMethod.isManual()) {366 markAsManual(method).accept(notifier);367 return;368 } else if (theMethod.isPending()) {369 markAsPending(method);370 notifier.fireTestIgnored(describeChild(method));371 return;372 } else {373 processTestMethodAnnotationsFor(method);374 }375 initializeTestSession();376 prepareBrowserForTest();377 additionalBrowserCleanup();378 performRunChild(method, notifier);379 if (failureDetectingStepListener.lastTestFailed() && maxRetries() > 0) {380 retryAtMost(maxRetries(), new RerunSerenityTest(method, notifier));381 }382 }383 private void retryAtMost(int remainingTries,384 RerunTest rerunTest) {385 if (remainingTries <= 0) { return; }386 logger.info(rerunTest.toString() + ": attempt " + (maxRetries() - remainingTries));387 StepEventBus.getEventBus().cancelPreviousTest();388 rerunTest.perform();389 if (failureDetectingStepListener.lastTestFailed()) {390 retryAtMost(remainingTries - 1, rerunTest);391 } else {392 StepEventBus.getEventBus().lastTestPassedAfterRetries(remainingTries,393 failureDetectingStepListener.getFailureMessages(),failureDetectingStepListener.getTestFailureCause());394 }395 }396 private void performRunChild(FrameworkMethod method, RunNotifier notifier) {397 super.runChild(method, notifier);398 }399 interface RerunTest {400 void perform();401 }402 class RerunSerenityTest implements RerunTest {403 private final FrameworkMethod method;404 private final RunNotifier notifier;405 RerunSerenityTest(FrameworkMethod method, RunNotifier notifier) {406 this.method = method;407 this.notifier = notifier;408 }409 @Override410 public void perform() {411 performRunChild(method, notifier);412 }413 @Override414 public String toString() {415 return "Retrying " + method.getDeclaringClass() + " " + method.getMethod().getName();416 }417 }418 private void clearMetadataIfRequired() {419 if (theTest.shouldClearMetadata()) {420 Serenity.getCurrentSession().clearMetaData();421 }422 }423 private void resetStepLibrariesIfRequired() {424 if (theTest.shouldResetStepLibraries()) {425 stepFactory.reset();426 }427 }428 protected void additionalBrowserCleanup() {429 // Template method. Override this to do additional cleanup e.g. killing IE processes.430 }431 private boolean shouldSkipTest(FrameworkMethod method) {432 return !tagScanner.shouldRunMethod(getTestClass().getJavaClass(), method.getName());433 }434 private void markAsPending(FrameworkMethod method) {435 testStarted(method);436 StepEventBus.getEventBus().testPending();437 StepEventBus.getEventBus().testFinished();438 }439 private Consumer<RunNotifier> markAsManual(FrameworkMethod method) {440 TestMethodConfiguration theMethod = TestMethodConfiguration.forMethod(method);441 testStarted(method);442 StepEventBus.getEventBus().testIsManual();443 StepEventBus.getEventBus().getBaseStepListener().latestTestOutcome().ifPresent(444 outcome -> outcome.setResult(theMethod.getManualResult())445 );446 switch(theMethod.getManualResult()) {447 case SUCCESS:448 StepEventBus.getEventBus().testFinished();449 return (notifier -> notifier.fireTestFinished(Description.EMPTY));450 case FAILURE:451 Throwable failure = new ManualTestMarkedAsFailure(theMethod.getManualResultReason());452 StepEventBus.getEventBus().testFailed(failure);453 return (notifier -> notifier.fireTestFailure(454 new Failure(Description.createTestDescription(method.getDeclaringClass(), method.getName()),failure)));455 case ERROR:456 case COMPROMISED:457 case UNSUCCESSFUL:458 Throwable error = new ManualTestMarkedAsError(theMethod.getManualResultReason());459 StepEventBus.getEventBus().testFailed(error);460 return (notifier -> notifier.fireTestFailure(461 new Failure(Description.createTestDescription(method.getDeclaringClass(), method.getName()),error)));462 case IGNORED:463 StepEventBus.getEventBus().testIgnored();464 return (notifier -> notifier.fireTestIgnored(Description.createTestDescription(method.getDeclaringClass(), method.getName())));465 case SKIPPED:466 StepEventBus.getEventBus().testSkipped();467 return (notifier -> notifier.fireTestIgnored(Description.createTestDescription(method.getDeclaringClass(), method.getName())));468 default:469 StepEventBus.getEventBus().testPending();470 return (notifier -> notifier.fireTestIgnored(Description.createTestDescription(method.getDeclaringClass(), method.getName())));471 }472 }473 private void testStarted(FrameworkMethod method) {474 getStepListener().testStarted(Description.createTestDescription(method.getMethod().getDeclaringClass(), testName(method)));475 }476 /**477 * Process any Serenity annotations in the test class.478 * Ignored tests will just be skipped by JUnit - we need to ensure479 * that they are included in the Serenity reports480 * If a test method is pending, all the steps should be skipped.481 */482 private void processTestMethodAnnotationsFor(FrameworkMethod method) {483 if (isIgnored(method)) {484 testStarted(method);485 StepEventBus.getEventBus().testIgnored();486 StepEventBus.getEventBus().testFinished();487 }488 }489 protected void prepareBrowserForTest() {490 if (theTest.shouldClearTheBrowserSession()) {491 WebdriverProxyFactory.clearBrowserSession(getDriver());492 }493 }494 /**495 * Running a unit test, which represents a test scenario.496 */497 @Override498 protected Statement methodInvoker(final FrameworkMethod method, final Object test) {499 if (webtestsAreSupported()) {500 injectDriverInto(test);501 initPagesObjectUsing(driverFor(method));502 injectAnnotatedPagesObjectInto(test);503 initStepFactoryUsing(getPages());504 }505 injectScenarioStepsInto(test);506 injectEnvironmentVariablesInto(test);507 useStepFactoryForDataDrivenSteps();508 Statement baseStatement = super.methodInvoker(method, test);509 return new SerenityStatement(baseStatement, stepListener.getBaseStepListener());510 }511 private void useStepFactoryForDataDrivenSteps() {512 StepData.setDefaultStepFactory(stepFactory);513 }514 /**515 * Instantiate the @Managed-annotated WebDriver instance with current WebDriver.516 * @param testCase A Serenity-annotated test class517 */518 protected void injectDriverInto(final Object testCase) {519 TestCaseAnnotations.forTestCase(testCase).injectDrivers(ThucydidesWebDriverSupport.getDriver(),520 ThucydidesWebDriverSupport.getWebdriverManager());521 dependencyInjector.injectDependenciesInto(testCase);522 }523 protected WebDriver driverFor(final FrameworkMethod method) {524 if (TestMethodAnnotations.forTest(method).isDriverSpecified()) {525 String testSpecificDriver = TestMethodAnnotations.forTest(method).specifiedDriver();526 return getDriver(testSpecificDriver);527 } else {528 return getDriver();529 }530 }531 /**532 * Instantiates the @ManagedPages-annotated Pages instance using current WebDriver.533 * @param testCase A Serenity-annotated test class534 */535 protected void injectScenarioStepsInto(final Object testCase) {536 StepAnnotations.injector().injectScenarioStepsInto(testCase, stepFactory);537 }538 /**539 * Instantiates the @ManagedPages-annotated Pages instance using current WebDriver.540 * @param testCase A Serenity-annotated test class541 */542 protected void injectAnnotatedPagesObjectInto(final Object testCase) {543 StepAnnotations.injector().injectAnnotatedPagesObjectInto(testCase, pages);544 }545 protected void injectEnvironmentVariablesInto(final Object testCase) {546 EnvironmentDependencyInjector environmentDependencyInjector = new EnvironmentDependencyInjector();547 environmentDependencyInjector.injectDependenciesInto(testCase);548 }549 protected WebDriver getDriver() {550 return (isEmpty(requestedDriver)) ? ThucydidesWebDriverSupport.getWebdriverManager().getWebdriver()551 : ThucydidesWebDriverSupport.getWebdriverManager().getWebdriver(requestedDriver);552 }553 protected WebDriver getDriver(final String driver) {554 return (isEmpty(driver)) ? ThucydidesWebDriverSupport.getWebdriverManager().getWebdriver()555 : ThucydidesWebDriverSupport.getWebdriverManager().getWebdriver(driver);556 }557 /**558 * Find the current set of test outcomes produced by the test execution.559 * @return the current list of test outcomes560 */561 public List<TestOutcome> getTestOutcomes() {562 return getStepListener().getTestOutcomes();563 }564 /**565 * @return The default reporters applicable for standard test runs.566 */567 protected Collection<AcceptanceTestReporter> getDefaultReporters() {568 return ReportService.getDefaultReporters();569 }570}...

Full Screen

Full Screen

getStepListener

Using AI Code Generation

copy

Full Screen

1import net.serenitybdd.junit.runners.SerenityRunner;2import net.thucydides.core.steps.StepEventBus;3import org.junit.runner.Description;4import org.junit.runner.notification.RunListener;5import org.junit.runner.notification.RunNotifier;6import org.junit.runners.model.InitializationError;7public class MySerenityRunner extends SerenityRunner {8 public MySerenityRunner(Class<?> klass) throws InitializationError {9 super(klass);10 }11 public void run(RunNotifier notifier) {12 notifier.addListener(getStepListener());13 super.run(notifier);14 }15 private RunListener getStepListener() {16 return new RunListener() {17 public void testStarted(Description description) throws Exception {18 super.testStarted(description);19 StepEventBus.getEventBus().testStarted(description.getDisplayName());20 }21 public void testFinished(Description description) throws Exception {22 super.testFinished(description);23 StepEventBus.getEventBus().testFinished();24 }25 };26 }27}

Full Screen

Full Screen

getStepListener

Using AI Code Generation

copy

Full Screen

1public class SerenityRunner extends SerenityRunner {2 public void run(final RunNotifier notifier) {3 notifier.addListener(new ReportListener());4 super.run(notifier);5 }6}7@RunWith(SerenityRunner.class)8public class SerenityTest {9 public void test() {10 }11}

Full Screen

Full Screen

getStepListener

Using AI Code Generation

copy

Full Screen

1import net.serenitybdd.junit.runners.SerenityRunner;2import net.thucydides.core.steps.StepListener;3import net.thucydides.core.steps.StepEventBus;4import org.junit.Test;5import org.junit.runner.RunWith;6import java.util.List;7import java.util.Map;8import java.util.stream.Collectors;9@RunWith(SerenityRunner.class)10public class SerenityRunnerTest {11 public void testSerenityRunner() {12 StepListener listener = getStepListener();13 List<Map<String, Object>> stepList = getStepList(listener);14 System.out.println(stepList);15 }16 private StepListener getStepListener() {17 return StepEventBus.getEventBus();18 }19 private List<Map<String, Object>> getStepList(StepListener listener) {20 return listener.getStepHistory().stream()21 .map(step -> Map.of(22 "title", step.getTitle(),23 "result", step.getResult(),24 "duration", step.getDurationInNanoseconds()25 .collect(Collectors.toList());26 }27}28[{29}, {30}, {31}]

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful