Java代码在从变量引用时可以正常运行,但直接调用时会抛出错误。

huangapple go评论66阅读模式
英文:

Java code works when referenced from a variable but throws an error when called directly

问题

我使用 AssertJ 库创建了一个断言。我将从 API 响应中的一个节点中提取的数据存储在一个字符串变量中,并在断言中引用了这个变量。这样是有效的,但是当直接将代码放在断言中时,会抛出 Predicate<Object> 错误。

//样式 1
JsonPath jsonPath = response.jsonPath();
String s = jsonPath.get("name"); //存储在一个变量中
Assertions.assertThat(s).contains("test"); //在这里引用时没有错误

//样式 2
JsonPath jsonPath = response.jsonPath();
Assertions.assertThat(jsonPath.get("name")).contains("test"); //直接使用时抛出错误

//错误信息
模糊的方法调用。Assertions 中的
assertThat
(Predicate&lt;Object&gt;)
和
assertThat
(IntPredicate)
都匹配
英文:

I created an assertion using AssertJ library. I stored the extraction from a node contained in an API response in a string variable. I referenced the variable in the assertion. It works, but when the code is passed directly in the assertion, it throws a Predicate<Object> error.

//Style 1
JsonPath jsonPath = response.jsonPath();
String s = jsonPath.get(&quot;name&quot;); //stored in a variable
Assertions.assertThat(s).contains(&quot;test&quot;); // no error when referenced here

//Style 2
 JsonPath jsonPath = response.jsonPath();
 Assertions.assertThat(jsonPath.get(&quot;name&quot;)).contains(&quot;test&quot;); //throws an error when used directly


//error
Ambiguous method call. Both
assertThat
(Predicate&lt;Object&gt;)
in Assertions&#160;and
assertThat
(IntPredicate)
in Assertions&#160;match

答案1

得分: 1

Assertions.assertThat((String)jsonPath.get("name"))
将其转换为字符串,它将起作用。

英文:

Assertions.assertThat((String)jsonPath.get("name"))
Cast to string it will work

答案2

得分: 1

这是一个叫做"模棱两可方法"的东西,基本上是因为 T 可以实现接口 I,而在 Assertions 中有一个 assertThat(I),使得编译器无法确定是使用 assertThat(String) 还是 assertThat(I)
所以在你的情况下,将方法转换为字符串:(String) jsonPath.get("name") 应该会起作用。

英文:

It is something called Ambiguous method, basically due to the fact that T could implement an interface I and there is an assertThat(I) in Assertions making the compiler confused whether to use assertThat(String) or assertThat(I).
So in your case, cast to string for the method: (String) jsonPath.get(&quot;name&quot;) should work

huangapple
  • 本文由 发表于 2020年7月26日 11:22:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63095764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定