Search⌘ K
AI Features

Message Consumer and Provider Example

Explore how to create and verify message contracts between consumers and providers in event-driven architecture using Pact. Understand the process of testing asynchronous message consumption and production, converting JSON payloads to protocol messages, and automating verification with Pact Broker. This lesson helps you validate integration points efficiently without relying on mock providers or consumers.

Contracts can also be developed by the consumers of asynchronous messages. We will want to expect messages from the consumers and verify that the providers will send the right messages. With asynchronous messaging, there will be no request portion to the test but only an incoming message to process. Likewise, for the provider, we will not receive any request for a message, so the testing pattern changes slightly.

Messaging contract testing with Pact

We will create tests for the messages that the Store Management module publishes, and test message consumption in both the Shopping Baskets and Depot modules.

The consumer tests are located in the /baskets/internal/handlers/integration_event_contract_test.go and /depot/internal/handlers/integration_event_contract_test.go files. These two modules receive messages from the Store Management module, which we will discuss later.

For each message that a consumer expects to receive, we must create an expected message entry in our contract with the following code:

message := pact.AddAsynchronousMessage()
for _, given := range tc.given {
message = message.GivenWithParameter(given)
}
assert.NoError(t, message.
ExpectsToReceive(name).
WithMetadata(tc.metadata).
WithJSONContent(tc.content).
AsType(&rawEvent{}).
ConsumedBy(msgConsumerFn).
Verify(t),
)
Creating an expected message entry in contract

The GivenWithParameter() and ExpectsToReceive() methods should be familiar to you if we read through the REST example. ...