Skip to content

Commit

Permalink
docs: Update docs with new consumer builder API
Browse files Browse the repository at this point in the history
  • Loading branch information
adamrodger committed Sep 1, 2022
1 parent 00a806e commit 8dfb3f2
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 67 deletions.
47 changes: 21 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,33 +77,29 @@ Pact tests have a few key properties. We'll demonstrate a common example using t
```csharp
public class SomethingApiConsumerTests
{
private readonly IPactBuilderV3 _pactBuilder;
private readonly IPactBuilderV3 pactBuilder;

public SomethingApiConsumerTests(ITestOutputHelper output)
public SomethingApiConsumerTests()
{
// Use default pact directory ..\..\pacts and default log
// directory ..\..\logs
var pact = Pact.V3("Something API Consumer", "Something API");
var pact = Pact.V3("Something API Consumer", "Something API", new PactConfig());

// or specify custom configuration such as pact file directory and serializer settings
// or specify custom log and pact directories
pact = Pact.V3("Something API Consumer", "Something API", new PactConfig
{
PactDir = @"..\pacts",
DefaultJsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
PactDir = $"{Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName}{Path.DirectorySeparatorChar}pacts"
});

// Initialize Rust backend
_pactBuilder = pact.UsingNativeBackend();
this.pactBuilder = pact.WithHttpInteractions();
}

[Fact]
public async Task GetSomething_WhenTheTesterSomethingExists_ReturnsTheSomething()
{
// Arrange
_pactBuilder
this.pactBuilder
.UponReceiving("A GET request to retrieve the something")
.Given("There is a something with id 'tester'")
.WithRequest(HttpMethod.Get, "/somethings/tester")
Expand All @@ -113,13 +109,12 @@ public class SomethingApiConsumerTests
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithJsonBody(new
{
// NOTE: These properties are case sensitive!
id = "tester",
firstName = "Totally",
lastName = "Awesome"
});

await _pactBuilder.VerifyAsync(async ctx =>
await this.pactBuilder.VerifyAsync(async ctx =>
{
// Act
var client = new SomethingApiClient(ctx.MockServerUri);
Expand All @@ -146,14 +141,14 @@ public class SomethingApiFixture : IDisposable

public SomethingApiFixture()
{
ServerUri = new Uri("http://localhost:9222");
ServerUri = new Uri("http://localhost:9223");
server = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls(ServerUri.ToString());
webBuilder.UseStartup<TestStartup>();
})
.Build();
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls(ServerUri.ToString());
webBuilder.UseStartup<TestStartup>();
})
.Build();
server.Start();
}

Expand All @@ -177,7 +172,7 @@ public class SomethingApiTests : IClassFixture<SomethingApiFixture>
[Fact]
public void EnsureSomethingApiHonoursPactWithConsumer()
{
//Arrange
// Arrange
var config = new PactVerifierConfig
{
Outputters = new List<IOutput>
Expand All @@ -191,11 +186,11 @@ public class SomethingApiTests : IClassFixture<SomethingApiFixture>
};

string pactPath = Path.Combine("..",
"..",
"path",
"to",
"pacts",
"Something API Consumer-Something API.json");
"..",
"..",
"..",
"pacts",
"Something API Consumer-Something API.json");

// Act / Assert
IPactVerifier pactVerifier = new PactVerifier(config);
Expand Down
72 changes: 37 additions & 35 deletions docs/messaging-pacts.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,49 +28,51 @@ public class StockEventProcessorTests
{
private readonly IMessagePactBuilderV3 messagePact;

public StockEventProcessorTests()
public StockEventProcessorTests(ITestOutputHelper output)
{
IMessagePactV3 v3 = MessagePact.V3("Stock Event Consumer", "Stock Event Producer", new PactConfig
IPactV3 v3 = Pact.V3("Stock Event Consumer", "Stock Event Producer", new PactConfig
{
// the location in which the pact file is written
PactDir = "../../../pacts/",

// the settings used to serialise each message by default
DefaultJsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
},
Outputters = new[]
{
new XUnitOutput(output)
}
});

this.messagePact = v3.UsingNativeBackend();
this.messagePact = v3.WithMessageInteractions();
}

[Fact]
public void RecieveSomeStockEvents()
public void ReceiveSomeStockEvents()
{
// define your expected message, using matchers for the message body
this.messagePact
.ExpectsToReceive("some stock ticker events")
.WithMetadata("key", "value")
.Given("A list of events is pushed to the queue")
.WithMetadata("key", "valueKey")
.WithJsonContent(Match.MinType(new
{
Name = Match.Type("AAPL"),
Price = Match.Decimal(1.23m)
Price = Match.Decimal(1.23m),
Timestamp = Match.Type(14.February(2022).At(13, 14, 15, 678))
}, 1))
.Verify<ICollection<StockEvent>>(events =>
{
// here we simply make sure it's expected, but we could run it through a real event processor
// to make sure it was processed properly. Warning - this is not meant for integration testing!
events.Should().BeEquivalentTo(new[]
{
new StockEvent
{
Name = "AAPL",
Price = 1.23m
Price = 1.23m,
Timestamp = 14.February(2022).At(13, 14, 15, 678)
}
});
});
}
}
```

After all of your consumer tests have passed a message pact file is written to disk. This file will be used
Expand Down Expand Up @@ -128,28 +130,28 @@ public class StockEventGeneratorTests : IDisposable
this.verifier
.MessagingProvider("Stock Event Producer", defaultSettings)
.WithProviderMessages(scenarios =>
{
// register the responses to each interaction
// the descriptions must match those in the pact file(s)
scenarios.Add("a single event", () => new StockEvent
{
Name = "AAPL",
Price = 1.23m
})
.Add("some stock ticker events", builder =>
{
builder.WithMetadata(new
{
ContentType = "application/json",
Key = "value"
})
.WithContent(new[]
{
new StockEvent { Name = "AAPL", Price = 1.23m },
new StockEvent { Name = "TSLA", Price = 4.56m }
});
});
})
{
// register the responses to each interaction
// the descriptions must match those in the pact file(s)
scenarios.Add("a single event", () => new StockEvent
{
Name = "AAPL",
Price = 1.23m
})
.Add("some stock ticker events", builder =>
{
builder.WithMetadata(new
{
ContentType = "application/json",
Key = "value"
})
.WithContent(new[]
{
new StockEvent { Name = "AAPL", Price = 1.23m },
new StockEvent { Name = "TSLA", Price = 4.56m }
});
});
})
.WithFileSource(new FileInfo(pactPath))
.Verify();
}
Expand Down
12 changes: 6 additions & 6 deletions samples/ReadMe/Provider.Tests/SomethingApiFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ public SomethingApiFixture()
{
ServerUri = new Uri("http://localhost:9223");
server = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls(ServerUri.ToString());
webBuilder.UseStartup<TestStartup>();
})
.Build();
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls(ServerUri.ToString());
webBuilder.UseStartup<TestStartup>();
})
.Build();
server.Start();
}

Expand Down

0 comments on commit 8dfb3f2

Please sign in to comment.