Best Serenity JUnit code snippet using net.serenitybdd.junit.runners.SerenityRunner.prepareBrowserForTest
Source:SerenityRunner.java
...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());...
Source:SerenityPageExtension.java
...38 if (testConfiguration.isAWebTest()) {39 applyTestClassOrTestMethodSpecificWebDriverConfiguration(extensionContext);40 initializeFieldsIn(extensionContext.getRequiredTestInstance());41 injectPageObjectIntoTest(extensionContext.getRequiredTestInstance());42 prepareBrowserForTest(extensionContext);43 }44 }45 private void applyTestClassOrTestMethodSpecificWebDriverConfiguration(final ExtensionContext extensionContext) {46 ThucydidesWebDriverSupport.clearDefaultDriver();47 final Optional<ExplicitWebDriverConfiguration> explicitWebDriverConfiguration = explicitWebDriverConfiguration(extensionContext);48 explicitWebDriverConfiguration.ifPresent(it -> {49 final String value = it.getTestSpecificDriver();50 final Consumer<String> consumer = ThucydidesWebDriverSupport::useDefaultDriver;51 notEmpty(value).ifPresent(consumer);52 notEmpty(it.getDriverOptions()).ifPresent(ThucydidesWebDriverSupport::useDriverOptions);53 workaroundForOtherwiseIgnoredWebDriverOptions();54 });55 }56 private Optional<String> notEmpty(final String value) {57 return ofNullable(value).filter(StringUtils::isNotEmpty);58 }59 /**60 * ThucydidesWebDriverSupport#getDriver creates the web driver used for the page factory (Pages). For the creation of the61 * the web driver options are only considered if a driver name is set. On the other hand TestCaseAnnotations#injectDrivers62 * which injects the driver into @Managed web driver fields of the test class, considers the options the @Managed annotation.63 * So if e.g. @Managed(options = "testOption") is used the web driver injected into the field has the defined options. But64 * the web driver injected into pages and steps does not have this option set. This is also the case in Junit4. Probably this65 * is a corner case that is usually not applied in real life. #66 *67 * options:68 * a) keep it as it is (consistent with Junit4)69 * b) change ThucydidesWebDriverSupport#getDriver to consider options also when no driver is set70 * c) consider this unintended usage => e.g. fail with an exception71 *72 * This method is basically a workaround for b until the serenity-core implementation is adjusted.73 */74 private void workaroundForOtherwiseIgnoredWebDriverOptions() {75 if (!ThucydidesWebDriverSupport.getDefaultDriverType().isPresent() && ThucydidesWebDriverSupport.getDefaultDriverOptions().isPresent()) {76 ThucydidesWebDriverSupport.useDefaultDriver(WebDriverConfiguredEnvironment.getDriverConfiguration().getDriverType().name()); // analog to net.thucydides.core.annotations.TestCaseAnnotations.configuredDriverType77 }78 }79 private Optional<ExplicitWebDriverConfiguration> explicitWebDriverConfiguration(final ExtensionContext extensionContext) {80 final Method testMethod = extensionContext.getRequiredTestMethod();81 final Class<?> requiredTestClass = extensionContext.getRequiredTestClass();82 if (hasExplicitWebDriverConfigurationOnTestMethod(testMethod)) {83 final String testSpecificDriver = TestMethodAnnotations.forTest(testMethod).specifiedDriver();84 final String driverOptions = TestMethodAnnotations.forTest(testMethod).driverOptions();85 return explicitWebDriverConfiguration(testSpecificDriver, driverOptions);86 } else if (hasExplicitWebDriverConfigurationOnTestClass(requiredTestClass)) {87 // CAUTION: unstable behaviour in case of multiple @Managed fields88 // findFirstAnnotatedField seems to be misleading. It finds "a" annotated field, because the ordering is not defined.89 // If there are multiple @Managed fields it is not clear which one should be used to define the default web driver used for the Steps.90 // So either A) this is an invalid use case that should be detected and rejected with an exception OR B) the default that would be used otherwise should be used91 // If net.thucydides.core.annotations.PatchedManagedWebDriverAnnotatedField.findAnnotatedFields would be public this case could at least be detected.92 // Note that even this block would be removed net.thucydides.core.annotations.TestCaseAnnotations#injectDrivers would still set a default but without explicitly93 // updating the PageFactory (which will happen as a side-effect to ThucydidesWebDriverSupport#getDriver calls.94 final ManagedWebDriverAnnotatedField firstAnnotatedField = ManagedWebDriverAnnotatedField.findFirstAnnotatedField(requiredTestClass);95 return explicitWebDriverConfiguration(firstAnnotatedField.getDriver(), firstAnnotatedField.getOptions());96 }97 return empty();98 }99 private void prepareBrowserForTest(final ExtensionContext extensionContext) {100 PatchedManagedWebDriverAnnotatedField.findAnnotatedFields(extensionContext.getRequiredTestClass()).stream()101 .filter(it -> ClearCookiesPolicy.BeforeEachTest.equals(it.getClearCookiesPolicy()))102 .map(it -> it.getValue(extensionContext.getRequiredTestInstance()))103 .forEach(WebdriverProxyFactory::clearBrowserSession);104 /* JUNIT4 analog impl:105 private void prepareBrowserForTest(TestConfiguration theTest) {106 if (theTest.shouldClearTheBrowserSession()) {107 // CAUTION: unstable behaviour in case of multiple @Managed fields108 // What is the expected behaviour in case of multiple @Managed fields? The current implementation picks an arbitrary @Managed field to decide109 // if a web driver instance should be cleared. It seems iterating over all @Manager fields and for those configured to clear the session, do so.110 // If net.thucydides.core.annotations.PatchedManagedWebDriverAnnotatedField.findAnnotatedFields would be public one could iterate easily111 // over the fields.112 WebdriverProxyFactory.clearBrowserSession(ThucydidesWebDriverSupport.getWebdriverManager().getCurrentDriver());113 }114 }115 */116 }117 @NotNull118 private Optional<ExplicitWebDriverConfiguration> explicitWebDriverConfiguration(final String testSpecificDriver, final String driverOptions) {119 return of(new ExplicitWebDriverConfiguration(testSpecificDriver, driverOptions));...
prepareBrowserForTest
Using AI Code Generation
1@RunWith(SerenityRunner.class)2public class MyTest extends SerenityRunner {3 public void test() {4 prepareBrowserForTest();5 }6}7public class MyTest {8 public void test() {9 SerenityRunner serenityRunner = new SerenityRunner();10 serenityRunner.prepareBrowserForTest();11 }12}13public class MyTest {14 public void test() {15 SerenityRunner serenityRunner = new SerenityRunner();16 serenityRunner.prepareBrowserForTest();17 }18}19public class MyTest {20 public void test() {21 SerenityRunner serenityRunner = new SerenityRunner();22 serenityRunner.prepareBrowserForTest();23 }24}25public class MyTest {26 public void test() {27 SerenityRunner serenityRunner = new SerenityRunner();28 serenityRunner.prepareBrowserForTest();29 }30}31public class MyTest {32 public void test() {33 SerenityRunner serenityRunner = new SerenityRunner();34 serenityRunner.prepareBrowserForTest();35 }36}37public class MyTest {38 public void test() {39 SerenityRunner serenityRunner = new SerenityRunner();40 serenityRunner.prepareBrowserForTest();41 }42}43public class MyTest {44 public void test() {45 SerenityRunner serenityRunner = new SerenityRunner();46 serenityRunner.prepareBrowserForTest();47 }48}
prepareBrowserForTest
Using AI Code Generation
1public void uploadFile(String filePath) throws AWTException {2 StringSelection ss = new StringSelection(filePath);3 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);4 Robot robot = new Robot();5 robot.keyPress(KeyEvent.VK_CONTROL);6 robot.keyPress(KeyEvent.VK_V);7 robot.keyRelease(KeyEvent.VK_V);8 robot.keyRelease(KeyEvent.VK_CONTROL);9 robot.keyPress(KeyEvent.VK_ENTER);10 robot.keyRelease(KeyEvent.VK_ENTER);11 }12public void uploadFile(String filePath) throws AWTException {13 StringSelection ss = new StringSelection(filePath);
prepareBrowserForTest
Using AI Code Generation
1public class MyFirstTest {2 public void myFirstTest() {3 }4}5public class MyFirstTest {6 public void myFirstTest() {7 }8}9public class MyFirstTest {10 public void myFirstTest() {11 }12}13public class MyFirstTest {14 public void myFirstTest() {15 }16}17public class MyFirstTest {18 public void myFirstTest() {19 }20}21public class MyFirstTest {22 public void myFirstTest() {23 }24}25public class MyFirstTest {26 public void myFirstTest() {27 }28}29public class MyFirstTest {30 public void myFirstTest() {31 }32}
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!!