Playwright with Cucumber/JUnit 5 - @BeforeAll @AfterAll @Before @After
Terence Pan
Posted on October 3, 2022
@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));
}
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();
}
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();
}
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();
}
As always code is on available on Github
Posted on October 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.