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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4052630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:35:14  来源:igfitidea点击:

assertEquals doesn't work without second parameter casting

javajunit

提问by Eugene

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

伙计们,为什么我会收到此 JUnit 测试的“方法 assertEquals(String, Object, Object) 对于类型 DictionaryTest 不明确”错误?

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

添加铸造assertEquals("test", (Integer)(a-b), c);解决了这个问题。

回答by Sean Patrick Floyd

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.

如果您将所有变量声明为 int(不是 Integer),则应该没有歧义。

回答by Cameron Skinner

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

这是因为编译器无法判断您是否要调用assertEquals(String, Object, Object)assertEquals(String, long, long)。由于a-bc可以自动强制到long编译器看到歧义。

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

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

Note that in this case you could use intrather than Integervariables which would also fix the ambiguity.

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