@@ -18,6 +18,7 @@ import au.com.dius.pact.core.model.generators.Category
18
18
import au.com.dius.pact.core.model.messaging.Message
19
19
import au.com.dius.pact.core.model.messaging.MessagePact
20
20
import au.com.dius.pact.core.model.v4.MessageContents
21
+ import org.json.JSONObject
21
22
import java.util.Locale
22
23
23
24
/* *
@@ -163,7 +164,7 @@ class MessagePactBuilder @JvmOverloads constructor(
163
164
*/
164
165
fun withContent (body : DslPart ): MessagePactBuilder {
165
166
if (messages.isEmpty()) {
166
- throw InvalidPactException (" expectsToReceive is required before withMetaData " )
167
+ throw InvalidPactException (" expectsToReceive is required before withContent " )
167
168
}
168
169
169
170
val message = messages.last()
@@ -197,7 +198,7 @@ class MessagePactBuilder @JvmOverloads constructor(
197
198
*/
198
199
fun withContent (xmlBuilder : PactXmlBuilder ): MessagePactBuilder {
199
200
if (messages.isEmpty()) {
200
- throw InvalidPactException (" expectsToReceive is required before withMetaData " )
201
+ throw InvalidPactException (" expectsToReceive is required before withContent " )
201
202
}
202
203
203
204
val message = messages.last()
@@ -231,7 +232,7 @@ class MessagePactBuilder @JvmOverloads constructor(
231
232
@JvmOverloads
232
233
fun withContent (contents : String , contentType : String = "text/plain"): MessagePactBuilder {
233
234
if (messages.isEmpty()) {
234
- throw InvalidPactException (" expectsToReceive is required before withMetaData " )
235
+ throw InvalidPactException (" expectsToReceive is required before withContent " )
235
236
}
236
237
237
238
val message = messages.last()
@@ -247,6 +248,35 @@ class MessagePactBuilder @JvmOverloads constructor(
247
248
return this
248
249
}
249
250
251
+ /* *
252
+ * Adds the JSON body as the message content
253
+ */
254
+ fun withContent (json : JSONObject ): MessagePactBuilder {
255
+ if (messages.isEmpty()) {
256
+ throw InvalidPactException (" expectsToReceive is required before withContent" )
257
+ }
258
+
259
+ val message = messages.last()
260
+ val metadata = message.contents.metadata.toMutableMap()
261
+ val contentTypeEntry = metadata.entries.find {
262
+ it.key.lowercase() == " contenttype" || it.key.lowercase() == " content-type"
263
+ }
264
+
265
+ var contentType = ContentType .JSON
266
+ if (contentTypeEntry == null ) {
267
+ metadata[" contentType" ] = contentType.toString()
268
+ } else {
269
+ contentType = ContentType (contentTypeEntry.value.toString())
270
+ }
271
+
272
+ message.contents = message.contents.copy(
273
+ contents = OptionalBody .body(json.toString().toByteArray(contentType.asCharset()), contentType),
274
+ metadata = metadata
275
+ )
276
+
277
+ return this
278
+ }
279
+
250
280
/* *
251
281
* Terminates the DSL and builds a pact to represent the interactions
252
282
*/
0 commit comments