0

I am trying to run Junit Parameterized test. Following is how Junit suggests to add data to collection of arrays.

Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };  
return Arrays.asList(data);  

This however requires user to add the data in the code. I want to read data from file (about 300 lines) and convert it into collection of Arrays. How can I do that ?

Here is the code:

import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;



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

    private String url;
    public static ArrayList<String>dataArray=new ArrayList<String>();
    static File directory = new File(".");
    public static String fileToRead;

    public UrlParameterizedTest(String url){
        this.url=url;
    }
    @Parameters
    public static Collection<Object[]> data() throws Exception {

        try {
            fileToRead=directory.getCanonicalPath()+"\\Data\\LinkChecker.csv";
            loadDataFile(fileToRead);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    Object[][]data=new Object[dataArray.size()][];
      *******   //convert dataArray to data here.************
        return Arrays.asList(data);

    }

    @Test
    public void testURLs() {
        System.out.println("Parameterized Number is "+url);
    }

    public static void loadDataFile(String dataFile) throws Exception {
        dataArray.clear();
        //if data_file is absolute, use this
        try
        {
            // Open an input stream
            // Read a line of text
            String line="";
            BufferedReader br=new BufferedReader(new FileReader(dataFile));
            while((line=br.readLine())!=null) {
                dataArray.add(line);
            }
            br.close();
            System.out.println("The data file length is "+ dataArray.size());
        }

        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println ("Unable to read from file");
        }
    }
}
3
  • can you be more detailed ? Commented Jan 31, 2013 at 11:40
  • @TechExchange : I guess OP wants to read inputs( 1,2,3,4 ) from file Commented Jan 31, 2013 at 11:43
  • @TechExchange: My questions is based on blogs.oracle.com/jacobc/entry/…. As Bhavik pointed out, I want to read {1},{2},{3},{4} from a CSV file. According to the above mentioned ref., Parameter's data method must return a collection of Arrays. Now, I already have a method that reads data from csv and puts that into an arrayList. I want to convert that arrayList into Object[][]data. In short, 300 lines in csv file should result in 300 parameterized test methods. Commented Feb 1, 2013 at 1:49

3 Answers 3

2

Use Apache Commons FileUtils.readFileToString to read the file to a string. Then you will need to parse the file into the collection of arrays. We cannot help you on how to parse the file and we don't know the contents.

FileUtils.readFileToString

Sign up to request clarification or add additional context in comments.

2 Comments

@Bhavik: List is a good option. How to turn that list into a collection of arrays ?
That depends on your file. You need to parse or group the lines into arrays. We don't know if each line is a comma-separated list of values or if you are going to combine a set of lines into an array or if each line is a single entry in the array. You have to figure SOME of these things out for yourself.
0

In order to retrieve strings from a File you could use something like the follow code; then you could retrieve data from your ArrayList and put them in your array (using "toArray()" method provided by Class ArrayList).

ArrayList<String> strings=new ArrayList<String >();
String filePath = path + "/" + fileName;

FileInputStream fin = null;
            try {
                fin = new FileInputStream(filePath);
            } catch (IOException e) {
                System.out.println (e.toString()); 
                System.out.println("File " + fileName + " not found.");
            }

            DataInputStream in = new DataInputStream(fin);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine = null;


            while ((strLine = br.readLine()) != null)   {

                strings.add(strLine);
            }

            in.close();

Comments

0

Put your data in a file, one under the other. Use a scanner to read them as strings and then convert them to numbers (I assumed that they should be float numbers). Something like this:

ArrayList<Float> numbers = new ArrayList<Float>();
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
    String nextLine = scanner.nextLine();
    float value = Float.parseFloat(nextLine);
    numbers.add(value);
}
scanner.close();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.