Wiremock : how to upload file to folder __files wi

2019-05-10 17:09发布

问题:

the documentation of wiremock says that we can mock a a request that retrieve a file thanks to this code :

{ "request": { "method": "GET", "url": "/body-file" }, "response": { "status": 200, "bodyFileName": "path/to/myfile.xml" } }

But now I have to find a way to reaaly upload the file other wise I have 500 error on the request.

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
    <title>Error 500 </title>
</head>
<body>
    <h2>HTTP ERROR: 500</h2>
    <p>Problem accessing /body-file. Reason:

        <pre>    java.lang.RuntimeException: java.io.FileNotFoundException: /wiremock-standalone/./__files/path/to/myfile.xml (No such file or directory)</pre>
    </p>
    <hr />
    <i>
        <small>Powered by Jetty://</small>
    </i>
</body>

Precision : I cannot upload the file directly due to our infrastructure constraints.

回答1:

Recent Wiremock versions have endpoint to manage stub files (see https://github.com/tomakehurst/wiremock/blob/2.19.0/src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java#L77)

You can upload a file with a PUT to /__admin/files/{filename}. There are stored under ${pwd}/__files.



回答2:

A workaround would be to use the "body" parameter, something like this:

{
    {
    "request": {
        "method": "GET",
        "url": "/body-file"
    },
    "response": {
        "status": 200,
        "body": "<example><node Id='1' Action='Insert' /></example>"
    }
}

(Note the single quotes in '1' vs. "1" - you'd need to escape those with \"1\".

See http://wiremock.org/docs/stubbing - Specifying the response body section.

If you need JSON payload, it's even nicer with the "jsonBody" parameter:

{
    {
    "request": {
        "method": "GET",
        "url": "/body-file"
    },
    "response": {
        "status": 200,
        "jsonBody": 
            { 
              "field1": "value1", 
              "field2" : "value2" 
            }
    }
}

Another nice feature is, quoting:

Stub mappings which have been created can be persisted to the mappings directory via a call to WireMock.saveAllMappings in Java or posting a request with an empty body to http://<host>:<port>/__admin/mappings/save.



标签: wiremock