java - 当 arraylist 包含对象时,如何使用 Junit/Java 测试 compareTo?

标签 java junit

我想测试一个比较对象中两个 double 值的 compareTo 方法。

我要测试的方法:

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

此方法比较双倍让分值(例如从 -1.0 到 5)。 对象:

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

我想为此创建一个测试方法,但不知道如何...

最佳答案

你可以这么简单地做到这一点。

@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");
}

因为你的 compareTo 方法是一个非常简单的方法,你实际上不需要测试它,我会说,因为它只是 Double#compareTo 完成了所有工作。但是,如果您在那里引入一些逻辑,那么它就会有意义。总体而言,您可以遵循以下模式:

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

关于java - 当 arraylist 包含对象时,如何使用 Junit/Java 测试 compareTo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62349054/

相关文章:

java - getMethods 是否可以按顺序使用反射?

java - 结果集在实体测试期间未正确定位

java - 使用 junitparams @FileParameter 在 Java : Combine 'custom test name' feature (@Parameters(name ="namestring")) in jUnit 4. 11 中进行参数化 jUnit 测试?

java - Maven/Surefire 没有找到单元测试

java - 为什么 nameList.add 不同步?

java - 如何确定我的应用程序是否在 Android 上运行

java - java中根据某个条件获取两个不同分隔符之间的某个子字符串

java - 在数组中测试 "getCustomer"方法时,预期值和实际值应该是什么?

Java自定义Exception错误未报告异常

java - 使用 Spring MVC 并发更新和检索