该方法如下所示。我只想返回一个Object [] 或者对象[] []或迭代器<对象[]>每行包含在for循环中创建的三个映射之一。我需要将所有字段(类别,用法,国家/地区)一起发送。
@DataProvider(name = "NewListings")
public Iterator<Object[]> AddNewListings(){
List<Map<String,String>> listings = new ArrayList<Map<String,String>>();
Map<String,String> listing = new HashMap<String, String>();
Random rand = new Random();
for (int i=0;i<3;i++){
listing.put("category", Integer.toString(rand.nextInt(8)+1));
listing.put("usage", Integer.toString(rand.nextInt(8)+1));
listing.put("country", Integer.toString(rand.nextInt(8)+1));
listings.add(listing);
//listing.clear();
}
Collection<Object[]> allListings = new ArrayList<Object[]>();
for(Map<String,String> map:listings){
allListings.add(new Object[]{map});
}
return allListings.iterator();
}
@Test(dataProvider = "NewListings")
public void addListing(Map<String, String> field){
//do stuff
}
答案 0 :(得分:0)
现在你在列表项上做了clear(),这意味着当for循环完成时,列表列表将包含一个对象,该对象将包含最后生成的值。 因此,将方法更改为此更好
public List<Map<Object,Object>> AddNewListings(){
List<Map<Object,Object>> listings = new ArrayList<Map<Object,Object>>();
Random rand = new Random();
for (int i=0;i<3;i++){
Map<Object,Object> listing = new HashMap<Object, Object>();
listing.put("category", Integer.toString(rand.nextInt(8)+1));
listing.put("usage", Integer.toString(rand.nextInt(8)+1));
listing.put("country", Integer.toString(rand.nextInt(8)+1));
listings.add(listing);
}
return listings;
}
然后你可以把它映射成一个数组
List<Map<Object, Object>> result = AddNewListings();
List<Object> out = new ArrayList<>();
for(Map<Object, Object> item : result) {
out.addAll(item.values());
}
Object[] allObjects2 = out.toArray();
当然,如果仅获取所有值的数组相关,则可以将AddNewListings方法更改为
public Object[] AddNewListings2(){
Random rand = new Random();
Object[] listings = new Object[9];
for (int i=0;i<9;i++){
listings[i] = Integer.toString(rand.nextInt(8)+1);
}
return listings;
}