Search code examples
javaintegration-testingpactpact-jvm

Using regex in pactdsl request body


I want my pact server to return a custom response when making a POST call with Header Content-Type: application/x-www-form-urlencoded.
However, the body of the POST call is not always the same, only a prefix remains constant.
For example, It has to return the same thing, whether I call it with body
input_text=LOGSomeStuffHERE, or with input_text=LOGAnoutherStuff
(As you see, input_text=LOG is the constant part) This is what I have tried:

.uponReceiving("POST cusom body")
.path("/path")
.method("POST")
.headers(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType())
.body("input_text=LOG*")
.willRespondWith()
.status(200)
...

Does PactDsl support some kind of body matching on the request part?


Solution

  • You can match using a Regex to validate your body. The body itself in the DSL is the actual body (with fake data) that is suppose to be returned for an interaction, without actually adding extra matchers. If you want an example of this, look at the test code for the jvm consumer.

    In your case, you'd do:

    .uponReceiving("POST cusom body")
    .path("/path")
    .method("POST")
    .headers(HttpHeaders.CONTENT_TYPE, 
       ContentType.APPLICATION_FORM_URLENCODED.getMimeType())
    .body(PactDslJsonRootValue.stringMatcher("^input_text\=LOG.*", 
       "input_text=LOG_something"))
    .willRespondWith()
    .status(200)
    

    The first argument is a string representation of the regex, while the second is the string to actually pass for the interaction, which need to pass the regex test.