Playwright with Cucumber/JUnit 5 - @BeforeAll @AfterAll @Before @After

terencepan

Terence Pan

Posted on October 3, 2022

Playwright with Cucumber/JUnit 5 - @BeforeAll @AfterAll @Before @After

@BeforeAll @AfterAll @Before @After

In the TestContext class we have a method annotated with @BeforeAll, this method will be called before any of the tests are run. These are things we want to do that are resource and time intensive and only want to do once. In this case we are initializing Playwright and the Browser classes on the computer to set up the framework and the browser.

    @BeforeAll
    public static void beforeAll(){
        playwright = Playwright.create();
        browser = playwright.chromium().launch(new BrowserType.LaunchOptions() // or firefox, webkit
                .setHeadless(false)
                .setSlowMo(100));
    }
Enter fullscreen mode Exit fullscreen mode

Method marked as @AfterAll is called after all the tests are run, and in this case we would like to close the Browser and Playwright so that they do not continue to use up resources.

    @AfterAll
    public static void afterAll(){
        browser.close();
        playwright.close();
    }
Enter fullscreen mode Exit fullscreen mode

Method marked as @Before is called before every test. In this case we want to open a new browser context for each test. Browser Contexts provide a way to operate multiple independent browser sessions. A page is a session in a browser context and we are creating one for each test.

    @Before
    public void createContextAndPage(){
        browserContext = browser.newContext();
        page = browserContext.newPage();
    }
Enter fullscreen mode Exit fullscreen mode

Method marked as @After is called after every test. In this case we want to close the browser context after each test.

    @After
    public void closeContext(){
        browserContext.close();
    }
Enter fullscreen mode Exit fullscreen mode

As always code is on available on Github

💖 💪 🙅 🚩
terencepan
Terence Pan

Posted on October 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related