Search code examples
javabddkarate

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


while I was automating the API using Karate, I came across a weird behavior where in I found org.graalvm.polyglot.PolyglotException while comparing response with the

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)

   

Now I have a java function definition like this -

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

When I run this feature it gives me the following error -

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.

Can you please help me solve this issue?

Thanks!


Solution

  • Because response is a JSON - which becomes a Map when you call Java, but your second argument in the Java method is a string.

    Add this line before the Java call, refer: https://github.com/intuit/karate#type-conversion

    * string response = response
    

    May I say something more ? I'm the author of Karate, and if you are using JSONAssert to do validations, you are making a HUGE mistake in my honest opinion. If someone else decided this, please let them know.