jeudi 9 avril 2015

IHTTPActionResult custom response and unit testing with WebApi 2

I have created a class which is as follows



public class Response<T> : IHttpActionResult where T : class
{
private readonly T _body;

....
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage msg = new HttpResponseMessage();

switch (_httpStatus)
{
case HttpResponseStatus.Ok:
{
msg = _request.CreateResponse(HttpStatusCode.OK, _body);
break;
}
case HttpResponseStatus.BadRequest:
{
msg = _request.CreateResponse(HttpStatusCode.BadRequest, _body);
break;
}
...
return Task.FromResult(msg);

}
}


This is my base class for returning IHTTPActionResult in my web api calls. It works well for what i require it for.


I now have some unit tests setup using MSTest.



// Act
IHttpActionResult result = controller.Step1();


// Assert
Assert.IsNotNull(result, "Is null when it shouldnt be");
Assert.IsInstanceOfType(result, typeof(Response<BodyContent<LogingActivityResult>>), "Is not expected IsInstanceOfType");


Both of these Assertions work fine. However i now want to actually get @ the data held within my response and assert that they are ok i.e.: correct values, counts, etc but am having no luck with this. I have tried ALL the various System.Web.Http.Results types such as



var contentResult = result as OkNegotiatedContentResult<Response<BodyContent<LogingActivityResult>>>;


or



var contentResult = result as FormattedContentResult<Response<BodyContent<LogingActivityResult>>>;


but both of these are null when i hover over contentResult variable.


Can anyone lead me in the right direction?


Thanks


Aucun commentaire:

Enregistrer un commentaire