How to send a byte array as a past of Json with ka

2019-07-23 14:30发布

I have an endpoint who consumes Json with 2 attributes, like

{id='12344', data=byte_array} 

so I've wrote a test

Feature: submitted request

Scenario: submitted request
* def convertToBytes =
"""
function(arg) {
    var StreamUtils = Java.type('my.utils.StreamUtils');
    // it reads stream and convert it to a byte array
    return StreamUtils.getBytes(arg);
}
"""

 Given url 'http://my-server/post'
 And def image = convertToBytes(read('classpath:images/image_1.jpg'));
 And request {id:1, data: "#(image)"}
 When method POST
 Then status 200

However is got an exception form karate without much details

ERROR com.intuit.karate - http request failed: [B cannot be cast to [Ljava.lang.Object;

Any hits how to submit byte arrays as a part of Json with karate?

标签: karate
1条回答
相关推荐>>
2楼-- · 2019-07-23 14:37

I don't think you can do that. Either the whole request should be binary (byte-array) or you do a multi-part request, where binary is Base64 encoded. As far as I know you can't put binary inside JSON. There is something called Binary JSON though.

EDIT: after assuming that the byte[] has to be Base64 encoded:

Background:
    * url demoBaseUrl
    * def Base64 = Java.type('java.util.Base64')

Scenario: json with byte-array
    Given path 'echo', 'binary'
    And def encoded = Base64.encoder.encodeToString('hello'.bytes);
    And request { message: 'hello', data: '#(encoded)' }
    When method post
    Then status 200
    And def expected = Base64.encoder.encodeToString('world'.bytes);
    And match response == { message: 'world', data: '#(expected)' }

I just added this test to the Karate demos, and it is working fine. Here is the commit.

查看更多
登录 后发表回答