如何为multipart / form-data上传cdc测试创建PACT

时间:2018-05-18 16:48:38

标签: unit-testing pact pact-jvm

我正在尝试创建用于上传文件验证的cdc测试。我用DIUS库。我没有找到如何在DIUS中使用.withFileUpload()的任何示例。我的pact代码是下一个:

@Pact(provider = PROVIDER, consumer = CONSUMER)
public RequestResponsePact createPact(PactDslWithProvider builder) throws Exception {
    DslPart responseBody = new PactDslJsonBody()
            .stringType("resource", DESTINATION_FILENAME)
            .stringType("requestId", null)
            .stringType("code", "201")
            .array("response")
            .closeArray()
            .asBody();

        return builder.given("UploadOperation")
                .uponReceiving("Upload operation")
                .path("/files/upload")
                .matchQuery("overwrite", "true")
                .matchQuery("destination_filename", DESTINATION_FILENAME)
                .withFileUpload("file",
                        ".gitignore",
                        "multipart/form-data", 
                         new byte[]{11,44,66,123,66}) // some bytes
                .willRespondWith()
                .status(201)
                .body(responseBody)
                .toPact();
        }

协议创建和验证代码:

    @Test
    @PactVerification
    public void doTest() throws IOException {
        String url = String.format("Http://localhost:%d/files/upload?overwrite=true&destination_filename=%s", PORT, DESTINATION_FILENAME);

        // HttpEntity for request
        HttpEntity multipart = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addBinaryBody("file", new byte[]{11,44,66,123,66}, 
                   ContentType.create("multipart/form-data"), ".gitignore")
                .build();

        // I make the request and get an answer                 
        HttpResponse response = Request.Put(url)
                .addHeader("Content-Type", "multipart/form-data; 
                   boundary=j72BRjsEynnAqDw43KTlsjxoKWsjdF_tl6N5")
                .body(multipart)
                .execute()
                .returnResponse();

        String json = EntityUtils.toString(response.getEntity());
        System.out.println("json=" + json);
        JSONObject jsonObject = new JSONObject(json);
        assertTrue(jsonObject.getString("code").equals("201"));
        assertTrue(response.getStatusLine().getStatusCode() == 201);}

但是当我运行测试时,我得到:json = {"错误":缺少开始边界}

java.lang.AssertionError: Pact Test function failed with an exception, possibly due to ExpectedButNotReceived(expectedRequests=[    method: PUT
path: /files/upload
query: [destination_filename:[test], overwrite:[true]]
headers: [Content-Type:multipart/form-data; boundary=iYxVLiQ0ZrP5g0SUP2pWa-rg20UM4JFe90p]
matchers: MatchingRules(rules={query=Category(name=query, matchingRules={overwrite=MatchingRuleGroup(rules=[RegexMatcher(regex=true, example=null)], ruleLogic=AND), destination_filename=MatchingRuleGroup(rules=[RegexMatcher(regex=test, example=null)], ruleLogic=AND)}), header=Category(name=header, matchingRules={Content-Type=MatchingRuleGroup(rules=[RegexMatcher(regex=multipart/form-data;(\s*charset=[^;]*;)?\s*boundary=.*, example=multipart/form-data; boundary=iYxVLiQ0ZrP5g0SUP2pWa-rg20UM4JFe90p)], ruleLogic=AND)}), path=Category(name=path, matchingRules={})})
generators: Generators(categories={})
body: OptionalBody(state=PRESENT, value=--iYxVLiQ0ZrP5g0SUP2pWa-rg20UM4JFe90p
Content-Disposition: form-data; name="file"; filename=".gitignore"
Content-Type: multipart/form-data

,B{B
--iYxVLiQ0ZrP5g0SUP2pWa-rg20UM4JFe90p--
)])

...
Caused by: org.json.JSONException: JSONObject["code"] not found.

s wrong in my code? I suppose something wrong with Content type, with 'boundary' part. But I don知道如何指定任意边界。 也许有人知道另一个库,其中实现了多部分/表单数据上传请求。

感谢。

1 个答案:

答案 0 :(得分:0)

我在DIUS库中找到了来自test example的解决方案

  1. .withFileUpload()中的contentType和相应的.addBinaryBody()方法不应该是" multipart / form-data"。它可能是" form-data"例如。
  2. .addHeader in request method不是必需的,因为内容类型已在body中定义。