How to use getBaseStepListener method of net.thucydides.junit.listeners.JUnitStepListener class

Best Serenity JUnit code snippet using net.thucydides.junit.listeners.JUnitStepListener.getBaseStepListener

Source:SerenityRunner.java Github

copy

Full Screen

...229            StepEventBus.getEventBus().dropAllListeners();230        }231    }232    private Optional<TestOutcome> latestOutcome() {233        if (StepEventBus.getEventBus().getBaseStepListener().getTestOutcomes().isEmpty()) {234            return Optional.empty();235        }236        return Optional.of(StepEventBus.getEventBus().getBaseStepListener().getTestOutcomes().get(0));237    }238    private void fireNotificationsBasedOnTestResultsTo(RunNotifier notifier) {239        if (!latestOutcome().isPresent()) {240            return;241        }242    }243    private void notifyTestSuiteFinished() {244        try {245            if (dataDrivenTest()) {246                StepEventBus.getEventBus().exampleFinished();247            } else {248                StepEventBus.getEventBus().testSuiteFinished();249            }250        } catch (Throwable listenerException) {251            // We report and ignore listener exceptions so as not to mess up the rest of the test mechanics.252            logger.error("Test event bus error: " + listenerException.getMessage(), listenerException);253        }254    }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) {...

Full Screen

Full Screen

Source:ThucydidesRunner.java Github

copy

Full Screen

...435        }436        injectScenarioStepsInto(test);437        useStepFactoryForDataDrivenSteps();438        Statement baseStatement = super.methodInvoker(method, test);439        return new ThucydidesStatement(baseStatement, stepListener.getBaseStepListener());440    }441    private void useStepFactoryForDataDrivenSteps() {442        StepData.setDefaultStepFactory(stepFactory);443    }444    /**445     * Instantiate the @Managed-annotated WebDriver instance with current WebDriver.446     * @param testCase A Thucydides-annotated test class447     * @param method the test method448     */449    protected void injectDriverInto(final Object testCase,450                                    final FrameworkMethod method) {451        TestCaseAnnotations.forTestCase(testCase).injectDriver(driverFor(method));452        dependencyInjector.injectDependenciesInto(testCase);453    }...

Full Screen

Full Screen

Source:JUnitStepListener.java Github

copy

Full Screen

...34        for(StepListener listener : extraListeners) {35            StepEventBus.getEventBus().registerListener(listener);36        }37    }38    public BaseStepListener getBaseStepListener() {39        return baseStepListener;40    }41    @Override42    public void testRunStarted(Description description) throws Exception {43        super.testRunStarted(description);44    }45    @Override46    public void testRunFinished(Result result) throws Exception {47        StepEventBus.getEventBus().testRunFinished();48        super.testRunFinished(result);49    }50    /**51     * Called when a test starts. We also need to start the test suite the first52     * time, as the testRunStarted() method is not invoked for some reason.53     */54    @Override55    public void testStarted(final Description description) {56        if (testingThisTest(description)) {57            startTestSuiteForFirstTest(description);58            StepEventBus.getEventBus().clear();59            StepEventBus.getEventBus().testStarted(description.getMethodName(),60                                                   description.getTestClass());61            startTest();62        }63    }64    private void startTestSuiteForFirstTest(Description description) {65        if (!getBaseStepListener().testSuiteRunning()) {66            StepEventBus.getEventBus().testSuiteStarted(description.getTestClass());67        }68    }69    @Override70    public void testFinished(final Description description) throws Exception {71        if (testingThisTest(description)) {72            StepEventBus.getEventBus().testFinished();73            endTest();74        }75    }76    @Override77    public void testFailure(final Failure failure) throws Exception {78        if (testingThisTest(failure.getDescription())) {79            startTestIfNotYetStarted(failure.getDescription());...

Full Screen

Full Screen

Source:JUnitStepListenerBuilder.java Github

copy

Full Screen

...66        }67    }68    private BaseStepListener buildBaseStepListener() {69        if (pageFactory != null) {70            return Listeners.getBaseStepListener()71                    .withPages(pageFactory)72                    .and().withOutputDirectory(outputDirectory);73        } else {74            return Listeners.getBaseStepListener()75                    .withOutputDirectory(outputDirectory);76        }77    }78    private JUnitStepListener newParameterizedJUnitStepListener() {79        return new ParameterizedJUnitStepListener(parameterSetNumber,80                parametersTable,81                testClass,82                buildBaseStepListener(),83                Listeners.getLoggingListener(),84                newTestCountListener());85//                Listeners.getStatisticsListener());86    }87    private StepListener newTestCountListener() {88        return JUnitInjectors.getInjector().getInstance(Key.get(StepListener.class, TestCounter.class));...

Full Screen

Full Screen

getBaseStepListener

Using AI Code Generation

copy

Full Screen

1import net.thucydides.core.annotations.Step;2import net.thucydides.core.steps.ScenarioSteps;3import net.thucydides.junit.listeners.JUnitStepListener;4public class SampleSteps extends ScenarioSteps {5    public void step1() {6        System.out.println("step1");7    }8    public void step2() {9        System.out.println("step2");10    }11    public void step3() {12        System.out.println("step3");13    }14    public void step4() {15        System.out.println("step4");16    }17}18import net.thucydides.junit.runners.ThucydidesRunner;19import org.junit.Test;20import org.junit.runner.RunWith;21@RunWith(ThucydidesRunner.class)22public class SampleTest {23    public void test() {24        SampleSteps steps = new SampleSteps();25        steps.step1();26        steps.step2();27        steps.step3();28        steps.step4();29        JUnitStepListener listener = steps.getBaseStepListener();30        System.out.println(listener.getStepCount());31    }32}

Full Screen

Full Screen

getBaseStepListener

Using AI Code Generation

copy

Full Screen

1public class BaseStepListener extends JUnitStepListener {2    public void testStarted(Description description) throws Exception {3        super.testStarted(description);4        getBaseStepListener().testStarted(description);5    }6}7public class MyStepListener extends BaseStepListener {8    public void testStarted(Description description) throws Exception {9        super.testStarted(description);10        getBaseStepListener().testStarted(description);11    }12}13public class MyStepListener extends BaseStepListener {14    public void testStarted(Description description) throws Exception {15        super.testStarted(description);16        getBaseStepListener().testStarted(description);17    }18}19public class MyStepListener extends BaseStepListener {20    public void testStarted(Description description) throws Exception {21        super.testStarted(description);22        getBaseStepListener().testStarted(description);23    }24}25public class MyStepListener extends BaseStepListener {26    public void testStarted(Description description) throws Exception {27        super.testStarted(description);28        getBaseStepListener().testStarted(description);29    }30}31public class MyStepListener extends BaseStepListener {32    public void testStarted(Description description) throws Exception {33        super.testStarted(description);34        getBaseStepListener().testStarted(description);35    }36}37public class MyStepListener extends BaseStepListener {38    public void testStarted(Description description) throws Exception {39        super.testStarted(description);40        getBaseStepListener().testStarted(description);41    }42}43public class MyStepListener extends BaseStepListener {44    public void testStarted(Description description) throws Exception {45        super.testStarted(description);46        getBaseStepListener().testStarted(description);47    }48}49public class MyStepListener extends BaseStepListener {50    public void testStarted(Description description) throws Exception {51        super.testStarted(description);52        getBaseStepListener().testStarted(description

Full Screen

Full Screen

getBaseStepListener

Using AI Code Generation

copy

Full Screen

1import net.thucydides.core.annotations.Step;2import net.thucydides.core.steps.ScenarioSteps;3import net.thucydides.junit.listeners.JUnitStepListener;4import org.junit.Test;5import org.junit.runner.Description;6import org.junit.runner.notification.Failure;7import org.junit.runner.notification.RunListener;8import org.junit.runner.notification.RunNotifier;9import org.junit.runners.model.InitializationError;10import java.lang.reflect.Field;11public class JUnitStepListenerTest extends ScenarioSteps {12    public void step1() {13        throw new AssertionError("step 1 failed");14    }15    public void test() throws InitializationError {16        RunNotifier notifier = new RunNotifier();17        notifier.addListener(new RunListener() {18            public void testFailure(Failure failure) throws Exception {19                super.testFailure(failure);20                Description description = failure.getDescription();21                if (description.getMethodName().equals("test")) {22                    JUnitStepListener baseStepListener = getBaseStepListener();23                    String stepFailureMessage = baseStepListener.getStepFailureMessage();24                    System.out.println(stepFailureMessage);25                }26            }27        });28        step1();29    }30    private JUnitStepListener getBaseStepListener() throws NoSuchFieldException, IllegalAccessException {31        Field baseStepListenerField = JUnitStepListener.class.getDeclaredField("baseStepListener");32        baseStepListenerField.setAccessible(true);33        JUnitStepListener baseStepListener = (JUnitStepListener) baseStepListenerField.get(null);34        return baseStepListener;35    }36}37	at net.thucydides.junit.listeners.JUnitStepListenerTest.step1(JUnitStepListenerTest.java:25)38	at net.thucydides.junit.listeners.JUnitStepListenerTest.test(JUnitStepListenerTest.java:34)

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 Serenity JUnit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful