Java 代码在从变量引用时有效,但在直接调用时抛出错误

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

我使用 AssertJ 库创建了一个断言。我将 API 响应中包含的节点的提取存储在字符串变量中。我在断言中引用了变量。它可以工作,但是当代码直接在断言中传递时,它会抛出谓词错误。

//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

Assertions.assertThat((字符串)jsonPath.get("姓名")) 投射到字符串它会起作用

它是一种叫做 Ambiguous 方法的东西,主要是因为 T 可以实现接口 I 并且断言中有一个 assertThat(I) 使编译器混淆是使用 assertThat(String) 还是 assertThat(I)。 因此,在您的情况下,将方法转换为字符串:(String) jsonPath.get("name") 应该有效