Ciri
Ciri

Reputation: 1

How to test an array of objects with junit in java

I'm new here, and I'm new to programming too. This is the code I'm writing, this is one of the two classes in the project, "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);


   }

 }


 }

And the other one, which consists of the method "Ordinator", that uses the bubble sort to put in order the "Students" based on the age, from the younger to the older:

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;
            }
        }
    }
}

Now I have to test the method order with Junit to see if it works. But I don't know how to test an array of objects, in particular in this situation. Hope someone can help! Thanks in advance :)

Upvotes: 0

Views: 3070

Answers (1)

phatfingers
phatfingers

Reputation: 10250

You just iterate your list, making individual comparisons.

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

Upvotes: 1

Related Questions