Best Serenity JUnit code snippet using net.serenitybdd.junit.runners.SerenityRunner.getDefaultReporters
Source:SerenityRunner.java  
...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}...Source:SerenityParameterizedRunner.java  
...190        getReportService().generateConfigurationsReport();191    }192    private ReportService getReportService() {193        if (reportService == null) {194            reportService = new ReportService(getOutputDirectory(), getDefaultReporters());195        }196        return reportService;197    }198    private Collection<AcceptanceTestReporter> getDefaultReporters() {199        return ReportService.getDefaultReporters();200    }201    private File getOutputDirectory() {202        return this.configuration.getOutputDirectory();203    }204    public void subscribeReporter(final AcceptanceTestReporter reporter) {205        getReportService().subscribe(reporter);206    }207    public List<Runner> getRunners() {208        return runners;209    }210}...Source:SerenityReportExtension.java  
...25    /**26     * @param testOutcomeResults the test results from the previous test run.27     */28    private void generateReportsFor(final List<TestOutcome> testOutcomeResults) {29        final ReportService reportService = new ReportService(getOutputDirectory(), getDefaultReporters());30        reportService.generateReportsFor(testOutcomeResults);31        reportService.generateConfigurationsReport();32    }33    /**34     *  @return The default reporters applicable for standard test runs.35     */36    protected Collection<AcceptanceTestReporter> getDefaultReporters() {37        return ReportService.getDefaultReporters();38    }39    public File getOutputDirectory() {40        return ConfiguredEnvironment.getConfiguration().getOutputDirectory();41    }42}...getDefaultReporters
Using AI Code Generation
1import net.serenitybdd.junit.runners.SerenityRunner;2import net.thucydides.core.reports.adaptors.xunit.model.TestCase;3import net.thucydides.core.reports.adaptors.xunit.model.TestSuite;4import net.thucydides.core.reports.adaptors.xunit.model.TestSuites;5import net.thucydides.core.reports.adaptors.xunit.model.TestSuitesSerializer;6import net.thucydides.core.reports.adaptors.xunit.model.TestSuitesSerializerFactory;7import net.thucydides.core.reports.adaptors.xunit.model.XUnitModel;8import net.thucydides.core.reports.adaptors.xunit.model.XUnitModelFactory;9import net.thucydides.core.reports.adaptors.xunit.model.XUnitModelParser;10import net.thucydides.core.reports.adaptors.xunit.model.XUnitModelParserFactory;11import net.thucydides.core.reports.adaptors.xunit.model.XUnitModelSerializer;12import net.thucydides.core.reports.adaptors.xunit.model.XUnitModelSerializerFactory;13import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestSuite;14import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestSuiteParser;15import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestSuiteParserFactory;16import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestSuiteSerializer;17import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestSuiteSerializerFactory;18import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCase;19import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCaseParser;20import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCaseParserFactory;21import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCaseSerializer;22import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCaseSerializerFactory;23import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCaseResult;24import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCaseResultParser;25import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCaseResultParserFactory;26import net.thucydides.core.reports.adaptors.xunit.model.XUnitTestCaseResultSerializer;27import net.thgetDefaultReporters
Using AI Code Generation
1import java.util.List;2import java.util.ArrayList;3import net.serenitybdd.junit.runners.SerenityRunner;4import net.thucydides.core.reports.TestOutcomes;5import net.thucydides.core.reports.TestOutcome;6import net.thucydides.core.reports.ReportType;7import net.thucydides.core.reports.Reporter;8import net.thucydides.core.reports.ReportService;9import net.thucydides.core.reports.html.HtmlAggregateStoryReporter;10import net.thucydides.core.reports.html.HtmlReporter;11import net.thucydides.core.reports.html.HtmlAcceptanceTestReporter;12import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForNonAngularSites;13import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForAngularSites;14import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForSinglePageApps;15import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebApps;16import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebSites;17import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebServices;18import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebServicesAndSinglePageApps;19import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebServicesAndWebApps;20import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebServicesAndWebSites;21import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebServicesAndWebAppsAndSinglePageApps;22import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebSitesAndSinglePageApps;23import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebAppsAndSinglePageApps;24import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebSitesAndWebApps;25import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebSitesAndWebAppsAndSinglePageApps;26import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebAppsAndWebSites;27import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebAppsAndWebSitesAndSinglePageApps;28import net.thucydides.core.reports.html.HtmlAcceptanceTestReporterForWebAppsAndgetDefaultReporters
Using AI Code Generation
1    public List<RunnerReporter> getDefaultReporters() {2        return new ArrayList<RunnerReporter>();3    }4    public List<RunnerListener> getDefaultListeners() {5        return new ArrayList<RunnerListener>();6    }7    public List<RunnerFilter> getDefaultFilters() {8        return new ArrayList<RunnerFilter>();9    }10    public List<RunnerListener> getDefaultClassListeners() {11        return new ArrayList<RunnerListener>();12    }13    public List<RunnerReporter> getDefaultClassReporters() {14        return new ArrayList<RunnerReporter>();15    }16    public List<RunnerFilter> getDefaultClassFilters() {17        return new ArrayList<RunnerFilter>();18    }19}20public boolean isDryRun()21public boolean isParallelClasses()22public boolean isParallelMethods()23public boolean isParallelSuites()24public boolean isParallelTestClasses()25public boolean isParallelTestMethods()26public boolean isParallelTestSuites()27public boolean isVerbose()28public boolean isVerboseClasses()29public boolean isVerboseTests()30public boolean isVerboseReporting()31public boolean isVerboseReportingOnly()32public boolean isVerboseReportingOnlyOnFailures()33public boolean isVerboseReportingOnlyOnFailuresOrErrors()34public boolean isVerboseReportingOnlyOnFailuresOrErrorsOrSkipped()35public boolean isVerboseReportingOnlyOnFailuresOrSkipped()36public boolean isVerboseReportingOnlyOnFailuresOrWarnings()37public boolean isVerboseReportingOnlyOnSkipped()38public boolean isVerboseReportingOnlyOnWarnings()39public boolean isVerboseReportingOnlyOnWarningsOrErrors()40public boolean isVerboseReportingOnlyOnWarningsOrErrorsOrSkipped()41public boolean isVerboseReportingOnlyOnWarningsOrSkipped()42public boolean isVerboseReportingOnFailures()43public boolean isVerboseReportingOnFailuresOrErrors()44public boolean isVerboseReportingOnFailuresOrErrorsOrSkipped()getDefaultReporters
Using AI Code Generation
1import java.util.List;2import java.util.ArrayList;3import net.thucydides.core.reports.ReportType;4import net.thucydides.core.reports.Reporter;5import net.thucydides.core.reports.ReporterFactory;6import net.thucydides.core.reports.html.HtmlAggregateStoryReporter;7import net.serenitybdd.junit.runners.SerenityRunner;8import org.junit.runner.RunWith;9import org.junit.runners.model.InitializationError;10@RunWith(SerenityRunner.class)11public class MyRunner extends SerenityRunner {12    public MyRunner(Class<?> klass) throws InitializationError {13        super(klass);14    }15    public List<Reporter> getDefaultReporters() {16        List<Reporter> reporters = new ArrayList<Reporter>();17        reporters.addAll(super.getDefaultReporters());18        reporters.add(new MyCustomReporter());19        return reporters;20    }21}22public class MyCustomReporter implements Reporter {23    public MyCustomReporter() {24    }25    public String getName() {26        return "MyCustomReporter";27    }28    public ReportType getReportType() {29        return ReportType.HTML;30    }31    public void generateReportsFor(TestOutcome testOutcome, File outputDirectory) throws IOException {32    }33    public void setOutputDirectory(File outputDirectory) {34    }35    public void setSourceDirectory(File sourceDirectory) {36    }37    public void setSystemConfiguration(SystemPropertiesConfiguration systemConfiguration) {38    }39    public void setEnvironmentVariables(EnvironmentVariables environmentVariables) {40    }41    public void setFavicon(URL favicon) {42    }43    public void setQualifier(String qualifier) {44    }45    public void setRequirementsTagProvider(RequirementsTagProvider requirementsTagProvider) {46    }47    public void setRequirementsTypes(RequirementsTypes requirementsTypes) {getDefaultReporters
Using AI Code Generation
1import net.serenitybdd.junit.runners.SerenityRunner2import net.thucydides.core.reports.json.JSONTestOutcomeReporter3import net.thucydides.core.reports.json.JSONTestOutcomeReporter$JSONTestOutcomeReporterFactory4import net.thucydides.core.reports.xml.XMLTestOutcomeReporter5import net.thucydides.core.reports.xml.XMLTestOutcomeReporter$XMLTestOutcomeReporterFactory6import org.junit.Test7import org.junit.runner.RunWith8@RunWith(SerenityRunner)9class SerenityRunnerTest {10    void test() {11        def defaultReporters = SerenityRunner.getDefaultReporters()12        def jsonReporter = new JSONTestOutcomeReporter(new JSONTestOutcomeReporter$JSONTestOutcomeReporterFactory())13        def xmlReporter = new XMLTestOutcomeReporter(new XMLTestOutcomeReporter$XMLTestOutcomeReporterFactory())14        SerenityRunner.setReporters(defaultReporters)15    }16}getDefaultReporters
Using AI Code Generation
1public class CustomSerenityRunner extends SerenityRunner {2    public CustomSerenityRunner(Class<?> klass) throws InitializationError {3        super(klass);4    }5    protected List<ReporterFactory> getDefaultReporters() {6        List<ReporterFactory> defaultReporters = super.getDefaultReporters();7        defaultReporters.add(new CustomSerenityReporterFactory());8        return defaultReporters;9    }10}11package net.serenitybdd.junit.runners;12import java.util.List;13public interface SerenityRunnerDelegate {14    List<ReporterFactory> getDefaultReporters();15}16package net.serenitybdd.junit.runners;17import java.util.List;18public class SerenityRunner extends SerenityRunnerDelegate {19    public SerenityRunner(Class<?> klass) throws InitializationError {20        super(klass);21    }22    protected List<ReporterFactory> getDefaultReporters() {23        return ImmutableList.of(new SerenityReporterFactory());24    }25}26package net.serenitybdd.junit.runners;27import java.util.List;28public class SerenityRunnerDelegate extends BlockJUnit4ClassRunner {29    public SerenityRunnerDelegate(Class<?> klass) throws InitializationError {30        super(klass);31    }32    protected List<ReporterFactory> getDefaultReporters() {33        return ImmutableList.of(new SerenityReporterFactory());34    }35}36package net.serenitybdd.junit.runners;37import java.util.List;38public class SerenityRunner extends BlockJUnit4ClassRunner {39    public SerenityRunner(Class<?> klass) throws InitializationError {40        super(klass);41    }42    protected List<ReporterFactory> getDefaultReporters() {43        return ImmutableList.of(new SerenityReporterFactory());44    }45}46package net.serenitybdd.junit.runners;47import java.util.List;48public class SerenityRunnerDelegate extends BlockJUnit4ClassRunner {49    public SerenityRunnerDelegate(Class<?> klass) throws InitializationError {50        super(klass);51    }52    protected List<ReporterFactory> getDefaultReporters() {53        return ImmutableList.of(new SerenityReporterFactory());54    }55}56package net.serenitybdd.junit.runners;57import java.util.List;58public class SerenityRunner extends BlockJUnit4ClassRunner {59    public SerenityRunner(Class<?> klass) throws InitializationLearn 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!!
