Search code examples
javaseleniumselenium-webdrivertestngtestng-dataprovider

Using Array as Parameter for Test Method


Commonly the parameters for the test method are as follows

 @Test //Test method (dataProvider="login")
public void TestCase1(String field1, String field2)
{
driver.findElement(By.xpath("//[@id='username']")).sendKeys(field1);
driver.findElement(By.xpath("//[@id='password']")).sendKeys(field2);
} 

The result is click on this image

Instead of specific (String field1, String field2) as the paremeters, is it possible for me to use array as the parameters (String[] fields)? (please see the code below)

 @Test //Test method (dataProvider="login")
public void TestCase1(String[] fields)
{
driver.findElement(By.xpath("//[@id='username']")).sendKeys(field[0]);
driver.findElement(By.xpath("//[@id='password']")).sendKeys(field[1]);
} 

The result is click on this image

From the results, there is slightly difference in terms of the formatting.

My question is does the both of the methods produce the same meaning?


Solution

  • There is clearly a difference.

    In first approach you are using String as an Object.

    The Second approach is using String array. You need to understand the basic difference between Arrays and String.

    You can refer arrays as a container which contains multiple Object/things of same type. And arrays obviously have fixed size in nature.

    Now array can be of String type, int type and etc..

    When you write String field1 , that's a single String object.

    But When you write String[] fields it is array of String objects, meaning it can have multiple String objects and you need to declare the size at the time of Initialization.

    Though in your scenario , both will produce the same result. Having said that you can increase the length of String[] and can use fields[0], fields[1], fields[2], fields[4] and so on..