Playwright with Cucumber/JUnit 5 - Dependency Injection with PicoContainer
Terence Pan
Posted on October 3, 2022
Dependency Injection
This project uses dependency injection to put the instance of TestContext into the step definition class. In a larger test project you would have multiple step definitions and you want an easy way to create common instances of things like the Playwright instance and BrowserContext. This also allows you to share data between steps in the same scenario like when we get and set the alert text.
This is implemented by including the maven dependency for pico-container earlier in the series and injecting this class through the Constructor of the step classes needing this class.
Constructor code in DemoSteps.java:
public DemoSteps(TestContext testContext) {
this.testContext = testContext;
this.browser = testContext.getBrowser();
}
Code using dependency injection to store alert text between steps in the same scenario:
@When("User clicks submit")
public void userClicksSubmit() {
DemoPage demoPage = new DemoPage(page);
String alertText = demoPage.clickSubmit();
testContext.setAlertText(alertText);
}
@Then("Verify alert {string}")
public void verifyAlertToFillInResultIsShown(String alertText) {
Assertions.assertEquals(alertText, testContext.getAlertText());
}
Full TestContext.java class
package io.tpan.steps;
import com.microsoft.playwright.*;
import io.cucumber.java.AfterAll;
import io.cucumber.java.BeforeAll;
public class TestContext {
protected static Playwright playwright;
protected static Browser browser;
protected BrowserContext browserContext;
protected Page page;
@BeforeAll
public static void beforeAll(){
playwright = Playwright.create();
browser = playwright.chromium().launch(new BrowserType.LaunchOptions() // or firefox, webkit
.setHeadless(false)
.setSlowMo(100));
}
@AfterAll
public static void afterAll(){
browser.close();
playwright.close();
}
public Browser getBrowser() {
return browser;
}
String alertText;
public String getAlertText() {
return alertText;
}
public void setAlertText(String alertText) {
this.alertText = alertText;
}
}
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.