如何在测试类里面测试collection集合里的元素

我想在测试类里面测试collection里面的元素,但是get方法似乎只适用于ArrayList,
/**
*@paramname
*@paramdescription
*@paramprice
*/
publicRecipe(Stringname,Stringdescription,doubleprice,Ingredient...ingredients){
if(name==null||name.isEmpty()){
thrownewIllegalArgumentException("namecan'tbenulloranemptystring");
}
this.name=name;
if(description==null||description.isEmpty()){
thrownewIllegalArgumentException("descriptioncan'tbenulloranemptystring");
}
this.description=description;
if(price<=0.00){
thrownewIllegalArgumentException("pricecan'tbelessorequalZERO!");
}
this.price=price;
if(ingredients==null){
thrownewIllegalArgumentException("ingredientscan'tbenulloranemptystring");
}
custmerOrderIngredients=newArrayList();
for(Ingredientingredient:ingredients){
custmerOrderIngredients.add(ingredient);
}
}
/**
*returntheingredientslist.
*@returnthecustmerOrderIngredients
*/
publicCollectiongetIngredients(){
return(ArrayList)custmerOrderIngredients;
}
上面是我的构造函数,因为规定了要用collection,我就只能这么写了,强制装换为ArrayList。然后测试代码我是这样的
@Test
publicvoidtestGetIngredients()throwsException{
Ingredientin1=newIngredient("burger");
Ingredientin2=newIngredient("chicken");
Reciper1=newRecipe("Beefburger","burgerwithbeef",5.00,in1,in2);
assertEquals("burger",r1.getIngredients().get(0).getName());
}
在Ingredient这个类里面只有一个元素name,所以我想取的是在Ingerdient里面的name,可是get(0)一直报错,我想问问使用是什么方式可以取到collection下的元素。Iterator()?
开满天机
浏览 351回答 2
2回答

哆啦的时光机

r1.getIngredients().get(0).getName()改成r1.getIngredients().iterator().next().getName()

泛舟湖上清波郎朗

你这样强转还有使用collection的必要呢?而且你还是不是转成list,而是arraylist!你这完全是挂着羊头卖狗肉啊
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript