-
-
Notifications
You must be signed in to change notification settings - Fork 11
Faking an Http response status
What: A response was received but it was not an HTTP 200 OK.
Why: There's plenty of reasons why the response might be any number of HTTP Status codes, which are not HTTP 200 OK
. Eg. An HTTP 500 SERVER ERROR
or an Authentication problem which returns an HTTP 401 UNAUTHORISED ERROR
, etc. An example why you should unit test for this is because imagine you require access to a locked down endpoint and your access token has expired, you might need to handle refreshing the access token and then re-attempting that data endpoint once more.
How: When we create the message handler, we set the HTTP Status we want to return.
How does this even work???: The trick was in our normal code where we call our endpoint ... we need to think about what happens when the result is not a 200 OK
. In my unit tests, if it's not 200 OK
I just throw an exception. You might want to do something more complex, like log this error, return a full error description and HTTP Status Code, etc.
[Fact]
public async Task GivenAServerError_GetSomeFooDataAsync_ThrowsAnException()
{
// Arrange.
// Fake response.
const string responseData = "Something Blew Up";
var messageResponse = FakeHttpMessageHandler.GetStringHttpResponseMessage(responseData,
HttpStatusCode.InternalServerError);
// Prepare our 'options' with all of the above fake stuff.
var options = new HttpMessageOptions
{
HttpResponseMessage = messageResponse
};
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 Should.ThrowAsync<InvalidOperationException>(myService.GetSomeFooDataAsync());
// Assert.
result.Message.ShouldStartWith(responseData);
}
- The Basics
- Common 'Happy Path' usages
- Common 'Sad Panda' usages
- Other interesting stuff