Skip to content

Commit e256c0c

Browse files
committed
feat: support MessagePact with a string as a content #1619
1 parent 68dd07f commit e256c0c

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

consumer/junit/src/test/groovy/au/com/dius/pact/consumer/junit/MessagePactBuilderSpec.groovy

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,4 +205,19 @@ class MessagePactBuilderSpec extends Specification {
205205
then:
206206
generators.categories[category] == ['$.DT': new DateTimeGenerator("yyyy-MM-dd'T'HH:mm:ss")]
207207
}
208+
209+
@Issue('#1619')
210+
def 'support non-json text formats'() {
211+
when:
212+
def pact = new MessagePactBuilder()
213+
.consumer('MessagePactBuilderSpec')
214+
.expectsToReceive('a message with text contents')
215+
.withContent('a=b&c=d', 'application/x-www-form-urlencoded')
216+
.toPact()
217+
Message message = pact.interactions.first()
218+
219+
then:
220+
message.contents.valueAsString() == 'a=b&c=d'
221+
message.contents.contentType.toString() == 'application/x-www-form-urlencoded'
222+
}
208223
}

consumer/src/main/kotlin/au/com/dius/pact/consumer/MessagePactBuilder.kt

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ import au.com.dius.pact.core.model.messaging.MessagePact
1717
/**
1818
* PACT DSL builder for v3 specification
1919
*/
20-
class MessagePactBuilder(
20+
class MessagePactBuilder @JvmOverloads constructor(
2121
/**
2222
* The consumer for the pact.
2323
*/
24-
private var consumer: Consumer,
24+
private var consumer: Consumer = Consumer(),
2525

2626
/**
2727
* The provider for the pact.
@@ -38,7 +38,6 @@ class MessagePactBuilder(
3838
*/
3939
private var messages: MutableList<Message> = mutableListOf()
4040
) {
41-
4241
/**
4342
* Name the provider that the consumer has a pact with.
4443
*
@@ -198,6 +197,24 @@ class MessagePactBuilder(
198197
return this
199198
}
200199

200+
/**
201+
* Adds the text as the message contents
202+
*/
203+
@JvmOverloads
204+
fun withContent(contents: String, contentType: String = "text/plain"): MessagePactBuilder {
205+
if (messages.isEmpty()) {
206+
throw InvalidPactException("expectsToReceive is required before withMetaData")
207+
}
208+
209+
val message = messages.last()
210+
message.metaData["contentType"] = contentType
211+
212+
val ct = ContentType(contentType)
213+
message.contents = OptionalBody.body(contents.toByteArray(ct.asCharset()), ct)
214+
215+
return this
216+
}
217+
201218
/**
202219
* Convert this builder into a Pact
203220
*/

0 commit comments

Comments
 (0)