Home > front end >  Importing Values from a Properties File for Automation Testing
Importing Values from a Properties File for Automation Testing

Time:12-24

I have to write a test that can print a value from a properties file using a dataprovider in TestNG. I am unsure where to begin. I have already completed the task using hardcoded values but cannot figure out to do so using the file. Here is what I have so far:

public class ConfigurationProvider {

    @DataProvider(name = "browserProvider")
    public FileInputStream getFile() throws IOException {
        
        FileInputStream fis = new FileInputStream(
                "C:\\Users\\user\\git\\Quntrix-Training\\automation\\src\\test\\resources\\config.properties");
        Properties p = new Properties();
        p.load(fis);
        p.getProperty("BrowserType");
                
        return fis;
    }
    
    @Test(dataProvider = "browserProvider")
    public void canPrintBrowser(String browserType) {
        System.out.println("The browser type is: "   browserType); 
    }
}

properties file looks like this:

Url=http://the-internet.herokuapp.com
BrowserType=chrome
ImplicitTimeout=5000
ScriptTimeout=5000

Running the test fails because it wants me to use Object[][]. But I am unsure how to fit it in. All the research I've done so far is just over complicated stuff using webdrivers etc... This should be basic but I'm new to this and it's really racking my brain.

CodePudding user response:

DataProvider requieres an Object[][] because that will be the two dimension array with the parameters of all executions of the @Test that uses that DataProvider.

For instance, if the Object[][] returned is this:

      data[0][0] = "Peter"; 
      data[0][1] = "18"; 

     data[1][0] = "Ross"; 
     data[1][1] = "45"; 

     data[2][0] = "Diana"; 
     data[2][1] = "11";

The @Test method, which must then be defined with 2 parameters, will be executed 3 times. The first one with the patameters Peter and 18, the second one with Ross and 45, and so on.

That is how a DataProvider works. So you will have to manually parse the properties file and with ots contents build the Object[][] that will serve the @Test method.

So your DataProvider method, simplofied for a single sample as in your question, should look like this:

@DataProvider(name = "browserProvider")
    public Object[][] getData() throws IOException {
        
        FileInputStream fis = new FileInputStream(
                "C:\\Users\\user\\git\\Quntrix-Training\\automation\\src\\test\\resources\\config.properties");
        Properties p = new Properties();
        p.load(fis);

        Object[][] data = new Object[1][1];
        data[0][0] = p.getProperty("BrowserType");
        return data;
    }

And if in the properties there is more data, just iterate or retrieve as you need and keep filling the Object[][].

  • Related