简体   繁体   中英

How can I compare two elements in a same array?

I want to write the test case with Junit for my ParOfDice class. But I do not know, how can I compare the elements of the same array. Not two differents array.

public class Wuerfelpaar {     // ParOfDice//

    //Erstellungs des Arrays
    private int[] wuerfel = new int[2];

    //Konstruktur des Klasses
    public Wuerfelpaar() {
        this.roll();
        this.pasch();
    }


    public void roll() {

        // Liefert die Länge vor der for-Schleife. Dies wird schneller sein, als wir es nicht sind
        // Immer wieder durch den Bereich navigieren.
        int length = wuerfel.length;
        for (int i = 0; i < length; ++i) {
            wuerfel[i] = (int) ((Math.random() * 6) + 1);
            System.out.println(wuerfel[i]);


        }
    }
    //Falls die Elemente des Arrays (beide Wuerfel) gleich sind
    //Kriegen wir eine Meldung, dass das Pasch ist.
    //Mit diese Struktur, sind die Klassen wiederrufbar.

    public void pasch(){
        if (wuerfel[0] == wuerfel[1]){
            System.out.println("PASCH");
        }
    }

}

Testing pasch()

I would add a getter method:

public int[] getWuerfel() {
   return wuerfel;
}

and a boolean verification method:

public boolean istPaar() {
   if(wuerfel[0] == wuerfel[1]) {
      return true;
   }
   return false;
}

to Wuerfelpaar . Then in your JUnit test you can do something like the following:

Wuerfelpaar wp = new Wuerfelpaar();
int[] wuerfel = wp.getWuerfel();
if(wp.istPaar()) {
   assertEqual(wuerfel[0], wuerfel[1]);
}
else {
   assertNotEqual(wuerfel[0], wuerfel[1]);
}

Other Tests

As far as other unit tests go, I don't think you really need to test other parts of this class. But if you are determined, I would write a test for roll() using the getter method above and then checking that both numbers in the wuerfel array are between 1 and 6 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM