简体   繁体   中英

Parametrization for BeforeEach, AfterEach in JUnit5 without ParameterResolver

How to parameterize @BeforeEach/@AfterEach annotated method in Junit 5? This method than should take arguments from passed stream or list of objects.

Suppose you have a base class BaseSmokeTest, where in @BeforeEach annotated method named prepare() the WebDriver is initialized. Now, other classes such as LoginSmokeTest or LogoutSmokeTest extends the BaseSmokeTest, so they do not care about the WebDriver initialization.

I would like to run parametrized tests for each browser. The only solution for me is to parameterize prepare() method with String parameter that will specify which browser to use - void prepare(String browserName)

I've tried to use ParameterResolver for resolving the parameter for prepare method, but if I understand this correctly, the ParameterResolver only resolves parameter for @BeforeEach/@AfterEach method once.

I also tried to parametrize Constructor, but again - the ParameterResolver only resolves parameter for constructor once.

I am looking for solution that would do something like this:

@ValueSource(strings = {"firefox", "chrome"})
@BeforeEach
public void prepare(String browserName) {
    WebDriver driver = initializeWebDriver(browserName);
    WebDriverRunner.initialize(driver);
}

@AfterEach
public void cleanup() {
    WebDriverRunner.closeWebDriver();
}

Edit: I should also state that desired functionality of these parameterized tests then would be parallelization - each browser should be launched parallel in its own session.

Edit2: I should also mention that the BaseSmokeTest (despite of the name) does not contain any tests at all, just the initialization of web driver necessary for other tests to run. Tests contain only the classes that extends the BaseSmokeTest.

If the number of different browsers is reasonably small you could go with a simple abstract test class approach. Here's a sketch:

abstract class BaseSmokeTest {
  abstract String getBrowserName();

  @BeforeEach
  public void prepare() {
    WebDriver driver = initializeWebDriver(getBrowserName());
    WebDriverRunner.initialize(driver);
  }

  @Test
  void test1() {}

  @Test
  void test2() {}
}

class FirefoxSmokeTest extends BaseSmokeTest {
  String getBrowserName() { return "firefox"; }
}


class ChromeSmokeTest extends BaseSmokeTest {
  String getBrowserName() { return "chrome"; }
} 

Jupiter will now run two test classes: ChromeSmokeTest and FirefoxSmokeTest . Each test method in BaseSmokeTest will be run twice, once for each concrete test class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM