I have a controller that generates an exception from the following code with the following message:-
public HttpResponseMessage PutABook(Book bookToSave)
{
return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Permission");
}
am testing this method with the following code:-
var response = controller.PutABook(new Book());
Assert.That(response.StatusCode,Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That(response.Content,Is.EqualTo("No Permission"));
But am getting an error that the content is not "No Permission". It seems I can't cast the response to an HttpError
either to get the message content "No Permission". The status code is returned fine. Just struggling to get the message content
.
As you figured in your comment, you could either use
response.Content.ReadAsAsync<HttpError>()
or you could also useresponse.TryGetContentValue<HttpError>()
. In both these cases, the content is checked to see if its of typeObjectContent
and the value is retrieved from it.You can try the following:
var errorContent = await response.Content.ReadAsAsync<HttpError>(); Assert.That(errorContent.Message,Is.EqualTo("No Permission"));
Try this one.
response.Content.ReadAsAsync<HttpError>().Result.Message;