如何使用空手道框架将字节数组作为 Json 的一部分发送
How to send a byte array as a part of Json with karate framework
我有一个端点使用 Json 和 2 个属性,比如
{id='12344', data=byte_array}
所以我写了一个测试
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
然而空手道有一个例外,没有太多细节
ERROR com.intuit.karate - http request failed: [B cannot be cast to [Ljava.lang.Object;
如何使用空手道提交字节数组作为 Json 的一部分?
我认为你做不到。不过 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。
编辑:假设 byte[] 必须是 Base64 编码后:
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)' }
我刚刚将此测试添加到空手道演示中,并且运行良好。这是 commit.
我有一个端点使用 Json 和 2 个属性,比如
{id='12344', data=byte_array}
所以我写了一个测试
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
然而空手道有一个例外,没有太多细节
ERROR com.intuit.karate - http request failed: [B cannot be cast to [Ljava.lang.Object;
如何使用空手道提交字节数组作为 Json 的一部分?
我认为你做不到。不过 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。
编辑:假设 byte[] 必须是 Base64 编码后:
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)' }
我刚刚将此测试添加到空手道演示中,并且运行良好。这是 commit.