org.graalvm.polyglot.PolyglotException 在空手道框架中比较 2 个字符串时 - Java

org.graalvm.polyglot.PolyglotException while comparing 2 Strings in Karate framework - Java

当我使用空手道使 API 自动化时,我遇到了一个奇怪的行为,在比较响应与

时我发现 org.graalvm.polyglot.PolyglotException
Scenario: create a user and then get it by id
    * def user = read('resources/request.json')
    * def assertResponse = Java.type('util.AssertResponse')
    * json expectedresponse = read('resources/response.json')
    * set expectedresponse.name = 'Test'

    Given url 'https://jsonplaceholder.typicode.com/users'
    And request user
    When method post
    Then status 201
    And assert response != null
    And print assertResponse.assertStringResponse(expectedresponse, response)

   

现在我有一个像这样的 java 函数定义 -

public static Boolean assertStringResponse(String expected, String actual) throws JSONException {
        JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT.LENIENT);
        return true;
    }

当我 运行 使用此功能时,出现以下错误 -

org.graalvm.polyglot.PolyglotException: TypeError: invokeMember (assertStringResponse) on util.AssertResponse failed due to: Cannot convert '{address={zipcode=54321-6789, suite=Apt. 123, city=Electri, street=Has No Name}, name=Test User, id=11, email=test@user.com, username=tes...'(language: Java, type: com.intuit.karate.graal.JsMap) to Java type 'java.lang.String': Invalid or lossy primitive coercion.

你能帮我解决这个问题吗?

谢谢!

因为 response 是 JSON - 当您调用 Java 时它变成 Map,但是 Java 方法中的第二个参数是字符串。

在Java调用之前添加这一行,参考:https://github.com/intuit/karate#type-conversion

* string response = response

我可以再说点什么吗?我是 Karate 的作者,如果您使用 JSONAssert 进行验证,我认为您犯了 HUGE 错误。如果其他人决定这样做,请让他们知道。