user2850361
user2850361

Reputation: 77

Use parameters in beforeclass in Junit

What I wan to do is read parameterized values and use them in the before class to set up a webdriver for the bowser as soecified by the parameter, the run the tests in the browser. Then get the next browser and run the test in that browser and so on for all the other specified browsers. But I am getting null values in the before class for the parmeters. Can you do this in Junit or is there another way of doing this?

Thanks

@RunWith(value = Parameterized.class)
public class MultiBrowser {

private static WebDriver driver;
private static  String browser;
//private static Dimension device;
private static String testData = "Testing";
private static String device;

@Parameters
public static Collection< Object[]> data() {
    System.out.println("Inside parameter");
    return Arrays.asList(new Object[][]{{"Firefox", "IPHONE4"},{"Chrome", "IPAD"},{"Ie", "SamsungGalaxy"}});
}

public MultiBrowser(String browser, String device){
    System.out.println("Inside MultiBrowser = "+ browser+" " + device);
    this.browser=browser;
    this.device=device;
}

@BeforeClass
public static void  dosetUp() throws Exception {
    System.out.println("Doing setup before class..." + browser + device);
 }

Upvotes: 2

Views: 3715

Answers (1)

Joe
Joe

Reputation: 31057

The technique you're using here won't work. @Parameters are injected through constructors, but your static @BeforeClass method is invoked before any constructor has been called, so those static fields will be null.

Your question is very similar to Creating a JUnit testsuite with multiple instances of a Parameterized test, and also Parameterized suites in Junit 4?; both answers suggest TestNG as a framework that is able to do this.

In JUnit, you could use the technique suggested by How do I Dynamically create a Test Suite in JUnit 4? to build a test suite dynamically and make do without using @Parameters.

Or, for a simpler but less efficient solution, move your setup code into a non-static @Before method and accept that it will run before every single test.

Upvotes: 1

Related Questions