简体   繁体   中英

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...

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 */

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...

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