Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring cloud contract: how to verify an array list (Kotlin based project)

I would like to write a groovy contract to verify an array list with string values. Lets say I have an object:

data class MyDataObject(val messageList: List<String>)

my contract is the following:

package contracts

import org.springframework.cloud.contract.spec.Contract

Contract.make {
   name("retrieve_list_of_objects")
   description("""
      given:
         you want to have a list of MyObjects
      when:
         you get the list
      then:
         you have the list
 """)
request {
    method 'GET'
    url '/10/my-objects'

    headers {
        contentType(applicationJson())
    }
}
response {
    status 200
    body(
           [ 
                   messageList: ["23412341324"]
           ]
    )
    headers {
        contentType(applicationJson())
    }
}   }

the problem is that created test is translated to:

assertThatJson(parsedJson).array("['messageList']").contains("23412341324").value();

and that results in:

com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['messageList'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.

The question is: how can I write my contract to create the following test:

assertThatJson(parsedJson).array("['messageList']").contains("23412341324");
like image 689
user3146276 Avatar asked Sep 05 '25 03:09

user3146276


1 Answers

I ran your snippet in my project and it generated a test that looks like this (I don't know why my test generating looks different than yours)

MockMvcRequestSpecification request = given()
                .header("Accept", "application/json")
                .body("{\"messageList\":[\"23412341324\"]}");

If I am reading your question right, you want the body to be a list of MyObjects, and not just one.

I think the problem is that you need to surround MyObject with one more set of square brackets, if indeed you want this to verify a list of MyObjects.

body(
       [[ 
               messageList: ["23412341324"]
       ]]
)

In General

Use SQUARE BRACKETS to make objects (yes i know in JSON square brackets are for arrays, its weird, i didn't invent it)

You can surround field names with quotes or without, they both seem to work.

body([
    stringField1: value(regex(".*")),
    stringField2: value(regex(alphaNumeric()),
    innerObject1: [
        innerStringField1: "Hardcoded1",
        innerIntegerField1: anyInteger()
    ]
])

Wait? How do I make JSON lists then if square brackets are for objects?

Double square brackets. Seriously.

body(
    [[
        stringFieldOfObjectInList: regex(".*")
    ]]
)
like image 131
Bradleo Avatar answered Sep 08 '25 00:09

Bradleo