Reputation: 573
This is my YAML file:
case 1: ["Jackson","23","Salt Lake City"]
case 2: ["Rachael","35","San Diego"]
#this will keep building and possibly have 1000 rows or so
I want these all into a 2D array like this:
{{"Jackson","23","Salt Lake City"},
{"Rachael","35","San Diego"}}
Basically I want to use these 2 sets of data in a TestNG data provider.
So I will create a DataProvider method which will return this 2D object. And the test method using this data provider will iterate through it. First it will take the "Jackson" data. The second round will take "Rachael" data.
I have used Jackson for serialization before like so:
public class TestCase {
@JsonProperty("Test")
private List<String> data;
public List<String> getData() {
return data;
}
public void setData(List<String> data) {
this.data = data;
}
}
But for this to work my YAML should be like so:
Test: ["Jackson","23","Salt Lake City"]
Test: ["Rachael","35","San Diego"]
But then the ObjectMapper only reads the last row. In this case the "Rachael" row.
Actually I don't care about "case 1" or "case 2". I want to write a method which will return an Object[][] containing the following:
{{"Jackson","23","Salt Lake City"},
{"Rachael","35","San Diego"}}
How do I achieve this inside my method?
I want this method to iterate through each row of the YAML file and put each row into an arraylist which stays inside the Object[][].
If you guys have better ways to manage test data using YAML please let me know.
Upvotes: 0
Views: 2505
Reputation: 36
If you don’t need keys (case 1, case 2) for your data, you can simplify your Yaml file
just change to
- ["Jackson","23","Salt Lake City"]
- ["Rachael","35","San Diego"]
then read as ArrayList by using SnakeYAML library and convert to Object[][]
You can try the next snippet in you DataProvider method
InputStream input = new FileInputStream(new File("path_to_your_file"));
ArrayList<ArrayList> list = (ArrayList<ArrayList>) new Yaml().load(input);
Object[][] data = list.stream()
.map(dataSet -> dataSet.toArray())
.toArray(Object[][]::new);
Handling test data is a common problem for automation QA’s. Choosing YAML files is already a good decision. We use Selenium Automation Bundle as it has already integrated a solution for test data. There is no description of the solution in Readme, but here it is an example of a test, and here it is an example of a file with test data which are enough to start using it. Though the bundle uses Groovy, you can write Java code in groovy classes without any doubts.
Upvotes: 2