英文:
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<Object>)
和
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("name"); //stored in a variable
Assertions.assertThat(s).contains("test"); // no error when referenced here
//Style 2
JsonPath jsonPath = response.jsonPath();
Assertions.assertThat(jsonPath.get("name")).contains("test"); //throws an error when used directly
//error
Ambiguous method call. Both
assertThat
(Predicate<Object>)
in Assertions and
assertThat
(IntPredicate)
in Assertions 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("name")
should work
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论