gpt4 book ai didi

java - 重载静态导入

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:36:33 25 4
gpt4 key购买 nike

在测试类中,我想提供我自己的 assertEquals 重载,其中包含一些不依赖于 Object.equals 的特殊逻辑。不幸的是,这不起作用,因为一旦我在本地声明我的 assertEquals 方法,Java 就不再从 org.junit.Assert.* 中找到静态导入.

有解决办法吗? IE。有没有办法为静态导入的方法提供额外的重载? (相当明显的解决方案是以不同的方式命名该方法,但该解决方案不具有相同的审美吸引力。)

我的测试类文件看起来像这样:

package org.foo.bar;

import static org.junit.Assert.*;

import org.junit.Test;

public class BarTest {
private static void assertEquals(Bar expected, Bar other) {
// Some custom logic to test equality.
}

@Test
public void testGetFoo() throws Exception {
Bar a = new Bar();
assertEquals(42, a.getFoo()); // Error *
}

@Test
public void testCopyConstructor() throws Exception {
Bar a = new Bar();
// Fill a.
Bar b = new Bar(a);
assertEquals(a, b);
}
}

错误 * 是“类型 BarTest 中的方法 assertEquals(Bar, Bar) 不适用于参数 (整数,整数)。”

最佳答案

这个答案分为两部分——一个关于编译错误,另一个关于 assertEquals() 的用法

问题是在两个不同的命名空间中有两个 assertEquals() 方法 - 一个存在于 org.junit.Assert 命名空间中,另一个存在于 org.foo.bar.BarTest 命名空间(当前命名空间)中。

由于 shadowing rules declared in the Java Language Specification 编译器报告错误. Assert.assertEquals() 的静态导入被 BarTest 类中声明的 assertEquals() 隐藏。

解决方法(总是在隐藏声明的情况下)是使用 FQN(完全限定名称)。如果您打算使用 JUnit 断言类的 assertEquals(...),请使用

org.junit.Assert.assertEquals(...)

当你需要使用你的声明时,只需使用

assertEquals(...)

仅在 BarTest 中,它被遮蔽。在所有其他只需要 Assert.assertEquals() 或 BarTest.asserEquals() 之一的类中,您可以导入 Assert 或 BarTest(我认为您不需要在其他地方导入 BarTest,但还是声明了)。

当没有阴影时,您可以简单地导入类或静态方法并在没有 FQN 的情况下使用它。

需要考虑的其他事项

Assert.assertEquals() 在内部使用参数类的 equals() 方法。在你的测试用例中声明一个 assertEquals() 违反了 DRY 原则,因为 equals() 类型的方法应该被一致地实现和使用——在源代码和单元测试中放置两个不同的实现势必会造成混淆。

最好的方法是在 Bar 上实现 equals(),然后在您的测试用例中使用 Assert.assertEquals()。如果您已经拥有,则不需要 BarTest.assertEquals()。 assertEquals() 的伪代码有点像下面这样

  1. 如果两个参数都为 null,则返回 true。
  2. 如果 expected 不为 null,则在 expected 上调用 equals(),将 actual 作为参数传递。如果对象相等则返回 true。
  3. 如果对象不相等,则抛出带有格式化消息的 AssertionError。

关于java - 重载静态导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1448723/

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