-
-
Notifications
You must be signed in to change notification settings - Fork 11
Multiple endpoints
Pure Krome edited this page Apr 26, 2017
·
4 revisions
What: faking multiple request endpoints
Why: unit testing a service that makes requests to multiple endpoints during one execution/run. For example, return the Order information and then the User Information (from two separate API endpoints) and return those two results into a single projection/instance.
How: Create a fake response for each endpoint the method calls.
Ok - so here's the main UNIT TEST class. For the full test code, please reference the tests here.
[Fact]
public async Task GivenSomeValidHttpRequests_GetSomeDataAsync_ReturnsAFoo()
{
// Arrange.
// 1. First fake response.
const string responseData1 = "{ \"Id\":69, \"Name\":\"Jane\" }";
var messageResponse1 = FakeHttpMessageHandler.GetStringHttpResponseMessage(responseData1);
// 2. Second fake response.
const string responseData2 = "{ \"FavGame\":\"Star Wars\", \"FavMovie\":\"Star Wars - all of em\" }";
var messageResponse2 = FakeHttpMessageHandler.GetStringHttpResponseMessage(responseData2);
// Prepare our 'options' with all of the above fake stuff.
var options = new[]
{
new HttpMessageOptions
{
RequestUri = new Uri("https://api.YouWebsite.com/something/here-1"), // Endpoint #1.
HttpResponseMessage = messageResponse1 // Fake response for this endpoint #1.
},
new HttpMessageOptions
{
RequestUri = new Uri("https://api.YouWebsite.com/something/here-2"), // Endpoint #2.
HttpResponseMessage = messageResponse2 // Fake response for this endpoint #2.
}
};
// 3. Use the fake responses if those urls are attempted.
var messageHandler = new FakeHttpMessageHandler(options);
var myService = new MyService(messageHandler);
// Act.
// NOTE: network traffic will not leave your computer because you've faked the response, above.
var result = await myService.GetAllDataAsync();
// Assert.
result.Id.ShouldBe(69); // Returned from GetSomeFooDataAsync.
result.Baa.FavMovie.ShouldBe("Star Wars - all of em"); // Returned from GetSomeBaaDataAsync.
options[0].NumberOfTimesCalled.ShouldBe(1);
options[1].NumberOfTimesCalled.ShouldBe(1);
}
- The Basics
- Common 'Happy Path' usages
- Common 'Sad Panda' usages
- Other interesting stuff