gpt4 book ai didi

junit - Assert.assertEquals junit 参数顺序

转载 作者:行者123 更新时间:2023-12-03 23:44:18 25 4
gpt4 key购买 nike

Assert.assertEquals 的参数顺序JUnit 中的方法是 (expected, actual)
虽然在另一个线程中有人说这是无缘无故的,但在我在 Uni 的一个 Java 类(class)中,教授提到了这种排序的具体原因,但我不记得了。

有人可以帮我解决这个问题吗?

最佳答案

  • 在工具/故障结果中正确标记 - 工具遵循此顺序,一些 GUI 工具会标记哪个值是预期值,哪个值是实际值。至少,如果标签与值匹配,它会尽量减少混淆;最坏的情况是,您花费时间/努力追踪错误的问题,试图追踪实际值的来源,而实际值实际上并不是实际值。
  • assertEquals 用法的一致性 - 如果您在整个断言中的顺序不一致,如果值在案例与案例之间任意交换,您可能会混淆 future 的您(或其他 future 的维护者),再次导致潜在的混淆。
  • 跨断言方法的一致参数排序 - assertEquals 可能是可逆的,但顺序可能对其他 assert* 方法(在 JUnit 的内置程序和其他支持代码/库中)很重要。最好在它们之间保持一致。
  • future 的变化 - 最后,在 future 的实现中可能会有所不同。
  • * 技术* - 它是预期值的 equals使用的方法:

  • 查看代码后有一个细微的区别。 assertEquals() 的许多用途最终将通过此方法运行:
    115 static public void assertEquals(String message, Object expected,
    116 Object actual) {
    117 if (expected == null && actual == null)
    118 return;
    119 if (expected != null && isEquals(expected, actual))
    120 return;
    ...
    128
    129 private static boolean isEquals(Object expected, Object actual) {
    130 return expected.equals(actual);
    131 }

    它的 equals当两个对象都不为空时使用的期望值的方法。有人可能会争辩说您知道期望值的类别(因此知道期望值类别的 equals 方法的行为),但您可能不一定知道实际值的类别(理论上可能有更宽松的 equals 方法)。因此,如果交换两个参数,您可能会得到不同的结果(即两个不同类的 equals 方法不是相互反射的):

    一个人为的情况是一个 ArrayList 的预期值和一个可以返回任何类型的 Collection 实例的实际值,可能是一个 ArrayList,但也可能是一个自定义 Collection 非列表类 'Foo' 的实例(即 Foo 确实不实现 List )。 ArrayList 的 equals方法(实际上是它的 AbstractList.equals )指定:

    Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.



    也许是“Foo”类的 equals方法更宽松地指定:

    Returns true if and only if the specified object is also a collection, both collections have the same size, and both collections contain equal objects but not necessarily in the same order.



    通过说:
    ArrayList expectArrayList = ...;
    Collection actualCollectionPossiblyFoo = ...
    Assert.assertEquals(expectedArrayList, actualCollectionPossiblyFoo)

    您是说您希望得到与 ArrayList 等效的东西(根据 ArrayList/AbstractList 对 equals 的定义)。这将失败,如果 actualCollectionPossiblyFoo真是一流 Foo因此不是 List作为
    ArrayList 需要 equals方法。

    然而,这与说:
    ArrayList expectedArrayList = ...;
    Collection actualCollectionPossiblyFoo = ...;
    Assert.assertEquals(actualCollectionPossiblyFoo, expectedArrayList);

    因为 actualCollectionPossbilyFoo可能是 Foo 的一个实例和
    Foo 可能会认为自己和 expectedArrayList等于根据 Foo类(class) equals方法。

    关于junit - Assert.assertEquals junit 参数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16267660/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com