0

I'm using JUnit and Selenium to do some browser testing, and need to run the same tests with multiple WebDrivers. To this end, I'm using JUnit parameterization so I can pass in an arbitrary number of WebDrivers at runtime and run the full test class for each driver.

Each driver should have .quit() called on it when it's no longer needed. Ideally, there would be an @AfterParameter method annotation that is called when each set of parameters are finished testing. In the absence of such an annotation, what's the cleanest way to avoid requiring test-writers to add a lot of boilerplate to their tests?

Here's what I have currently:

@Parameters(name = "{0}")
public static Collection<Object[]> config() throws IOException {

    return SeleniumCore.getConfig();
}

private static WebDriver driver;
private static Collection<WebDriver> oldDrivers = new ArrayList<>();


public TestingClass(String name, SeleniumTestParameters params) {

    // Stores old open drivers to be closed down at the end of testing.
    if (TestingClass.driver != null) {
        oldDrivers.add(driver);
    }

    TestingClass.driver = params.getDriver();
}


@AfterClass
public static void afterClass() {

    for (WebDriver oldDriver : oldDrivers) {
        oldDriver.quit();
    }
    driver.quit();
}

It allows for old drivers to be stored until the entire class gets torn down, and it works properly. However, it also requires extra boilerplate in both the constructor and the afterClass methods, as well as an additional piece of information. Is it possible to clean this up?

Brian Bauman
  • 668
  • 5
  • 22
  • This looks like an abuse of parametrization to do configuration. Instead, you should probably make your tests use some configuration file or environment variable to determine the driver, and start the tests separately for each driver. Related: https://stackoverflow.com/questions/9263077, https://stackoverflow.com/questions/30353996 – tkruse Jan 17 '18 at 01:18
  • I am loading from a config file - I have a method that loads various config options into a parameter matrix (currently [webDrivers x userTypes], but it can have as many dimensions as I like) that each testing class consumes. Is there a reason to *not* use parameters to pass in these sets of run-time variables? The SO questions you provided, while informative and useful, don't seem to weigh in on that. – Brian Bauman Jan 17 '18 at 16:43
  • Using those variables prevents from using parametrized tests for real test parameters. Other than that it is a mere matter of taste I guess. – tkruse Jan 18 '18 at 01:03

1 Answers1

2

The upcoming (yet unreleased) version 4.13 of JUnit supports @AfterParam and @BeforeParam: https://github.com/junit-team/junit4/pull/1435

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72