Search code examples
selenium-webdriverjunit5parameterized-unit-test

How to Parameterize beforeEach() in JUnit 5?


I am using JUnit 5 as my Test Runner.

In the setup method, I have hardcoded 3 params (platformName, platformVersion, and deviceName). I have a test method that should test on various combinations... This means, when running my testLogin() test, it should run on multiple platform names, versions, device names...

So, I tried as below...

@BeforeEach
@CsvSource({"IOS,13.0,iPhone X Simulator", "IOS,13.2,iPhone Simulator", "IOS,13.3,iPhone XS Simulator"})
void setUp(String platformName, String platformVersion, String deviceName) throws MalformedURLException {
    ....
    capabilities.setCapability("platformName", platformName);
    capabilities.setCapability("platformVersion", platformVersion);
    capabilities.setCapability("deviceName", deviceName);
    capabilities.setCapability("methodName", testInfo.getDisplayName());
}

My question is, how can beforeEach() method can be parameterized? Also, I want to get the test method name... So, if I specify the parameters, then where should I specify TestInfo param.

Please help me. I have also seen the below question...

Parameterized beforeEach/beforeAll in JUnit 5

========

public class TestBase {

    @BeforeEach
    void setUp(TestInfo testInfo) throws MalformedURLException {
        MutableCapabilities capabilities = new MutableCapabilities();
        capabilities.setCapability("platformName", "iOS");
        capabilities.setCapability("platformVersion", "13.2");
        capabilities.setCapability("deviceName", "iPhone Simulator");
        capabilities.setCapability("name", testInfo.getDisplayName());
        capabilities.setCapability("app", “/home/my-user/testapp.zip");

        driver = new IOSDriver(
                new URL("https://192.168.1.4:5566/wd/hub"),
                capabilities
        );
    }
}
public class LoginTest extends TestBase {

    @Test
    public void testLogin() {
        driver.findElement(By.id("user-name")).sendKeys(“myuser);
        driver.findElement(By.id("password")).sendKeys(“mypassword);
        driver.findElement(By.id(“login_btn”)).click();
        assertTrue(true);
    }
}

Solution

  • You can't parameterize @BeforEach method. JUnit5 supports only parameterized tests (test methods).

    Parameterized tests are declared just like regular @Test methods but use the @ParameterizedTest annotation instead. In addition, you must declare at least one source (e.g. @CsvSource, @ValueSource, etc.)

    For example:

        @ParameterizedTest
        @CsvSource({
            "apple,         1",
            "banana,        2",
            "'lemon, lime', 0xF1"
        })
        void testWithCsvSource(String fruit, int rank) {
            assertNotNull(fruit);
            assertNotEquals(0, rank);
        }