gpt4 book ai didi

java - 如何在java中使用junit测试对象数组

转载 作者:行者123 更新时间:2023-12-02 13:22:04 25 4
gpt4 key购买 nike

我是新来的,我也是编程新手。这是我正在编写的代码,这是项目中的两个类之一,“Student”:

interface Comparable{
public boolean youngerThan(Comparable c);
}

public class Student implements Comparable{
private String name;
private int age;


public Student(String n, int a){
this.name=n;
this.age=a;
}

public String getName(){
return this.name;
}

public int getAge(){
return this.age;
}
public void setStudent(String n, int a){
this.name=n;
this.age=a;
}
public String toString() {

return this.getName()+" ("+this.getAge()+"years)";
}
public boolean youngerThan(Comparable c){
Student s;
s=(Student)c;
if(this.getAge()>s.getAge())
return false;
if (this.getAge()==s.getAge())
return false;
else
return true;
}

public static void main(String[] args){
Student[] student= new Student[5];

student[0].setStudent("Marco", 20);
student[1].setStudent("Giacomo", 19);
student[2].setStudent("Susan", 24);
student[3].setStudent("Billie", 25);
student[4].setStudent("Max", 18);


}

}


}

另一个由“Ordinator”方法组成,它使用冒泡排序根据年龄(从年轻到年长)对“学生”进行排序:

public class Ordinator {
public static void order(Comparable[]list){
int imin;
for(int ord=0; ord<list.length-1;ord++){
imin=ord;
for(int i=ord +1; i<list.length; i++){
if(list[i].youngerThan(list[imin]));
Comparable temp=list[i];
list[i]=list[imin];
list[imin]=temp;
}
}
}
}

现在我必须使用 Junit 测试方法顺序,看看它是否有效。但我不知道如何测试对象数组,特别是在这种情况下。希望有人可以帮忙!预先感谢:)

最佳答案

您只需迭代您的列表,进行单独比较。

for (int i=1; i<list.length; i++) {
assertTrue(list[i].compareTo(list[i-1]) >= 0);
}

关于java - 如何在java中使用junit测试对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43526621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com