Ronny Giezen
Ronny Giezen

Reputation: 647

How can I test a compareTo with Junit/Java when the arraylist contains objects?

I want to test a compareTo method that compares two double values from an object.

Method I want to test:

public int compareTo(Participant other) {
        return Double.compare(this.handicap, other.handicap);
    }

This method compares the Handicap double values (from -1.0 to 5 for example). The object:

public Participant(String naam, double handicap, String thuisbaan) {
        this.naam = naam;
        this.handicap = handicap;
        this.thuisbaan = thuisbaan;
    }

I want to create an test method for this, but don't know how...

Upvotes: 4

Views: 4046

Answers (1)

Mansur
Mansur

Reputation: 1829

You can do it as simple as this.

@Test
void testCompareTo() {
    // given:
    Participant james = new Participant("James", 12.0, "Random1");
    Participant jane = new Participant("Jane", 212.0, "Random2");
    // when: then:
    Assertions.assertEquals(-1, james.compareTo(jane), "Should James be smaller than Jane");

    // given:
    james = new Participant("James", 12.0, "Random1");
    jane = new Participant("Jane", 12.0, "Random2");
    // when: then:
    Assertions.assertEquals(0, james.compareTo(jane), "Should James and Jane be equal");

    // given:
    james = new Participant("James", 212.0, "Random1");
    jane = new Participant("Jane", 12.0, "Random2");
    // when: then:
    Assertions.assertEquals(1, james.compareTo(jane), "Should James be bigger than Jane");
}

Since your compareTo method is a very trivial one, you do not actually need to test it, I would say, because it is just Double#compareTo that does all the work. However, if you introduce a bit of logic there, then it will make sense. Overall, you can follow this pattern:

// given:
/* initialize all your objects here, including mocks, spies, etc. */
// when:
/* the actual method invocation happens here */
// then:
/* assert the results, verify mocks */

Upvotes: 5

Related Questions