如果没有第二个参数转换,assertEquals 将不起作用

发布于 2024-09-30 03:33:07 字数 326 浏览 1 评论 0原文

各位,为什么我在这个 JUnit 测试中收到“方法 assertEquals(String, Object, Object) 对于类型 DictionaryTest 来说不明确”错误?

@Test
 public void testEditCard() {
  Integer a = 10;
  Integer b = 12;
  Integer c = 2;
  assertEquals("test", a-b, c);
 }

添加强制转换 assertEquals("test", (Integer)(ab), c); 可以解决该问题。

Folks, why I'm getting the "The method assertEquals(String, Object, Object) is ambiguous for the type DictionaryTest" error for this JUnit test?

@Test
 public void testEditCard() {
  Integer a = 10;
  Integer b = 12;
  Integer c = 2;
  assertEquals("test", a-b, c);
 }

Adding casting assertEquals("test", (Integer)(a-b), c); resolves the problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

離殇 2024-10-07 03:33:07

由于自动装箱和拆箱的奇迹:

assertEquals("test", /* this is an int */ a-b, /* this is an Integer */ c);

可以计算为

assertEquals(String, long, long);
// in this case the second parameter is unboxed
// (and the first one silently casted)

或为

assertEquals(String, Object, Object);
// in this case the first parameter is boxed

如果将所有变量声明为 int (而不是 Integer),那么应该不会有歧义。

Because of the wonders of autoboxing and -unboxing:

assertEquals("test", /* this is an int */ a-b, /* this is an Integer */ c);

Can be evaluated as

assertEquals(String, long, long);
// in this case the second parameter is unboxed
// (and the first one silently casted)

or as

assertEquals(String, Object, Object);
// in this case the first parameter is boxed

If you declare all variables as int (not Integer), there should be no ambiguity.

二手情话 2024-10-07 03:33:07

这是因为编译器无法判断您是否要调用 assertEquals(String, Object, Object) 还是 assertEquals(String, long, long)。由于 abc 可以自动强制为 long,因此编译器会出现歧义。

您的显式转换告诉编译器您需要对象版本。

请注意,在这种情况下,您可以使用 int 而不是 Integer 变量,这也可以解决歧义。

It's because the compiler can't tell if you want to call assertEquals(String, Object, Object) or assertEquals(String, long, long). Since a-b and c can be automatically coerced to long the compiler sees an ambiguity.

Your explicit cast tells the compiler that you want the Object version.

Note that in this case you could use int rather than Integer variables which would also fix the ambiguity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文