mercredi 1 juin 2016

Unit test for a Web API method without any injected dependency

I have a method in my Web API project and since it's pretty simple and there is no injected dependency and it deals with a concrete POSTed object, I'm not sure how I could create a unit test for it. Is there anything in the design of the below code I could change to make it more test-friendly?

public class HomeController : ApiController
{
    public HttpResponseMessage Post(RootObject root)
    {
        HttpResponseMessage httpResponse;

        return TryCreateResponse(root, out httpResponse) ? httpResponse : Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An unhandled exception occurred on the server.");
    }

    private bool TryCreateResponse(RootObject root, out HttpResponseMessage httpResponse)
    {
        var success = false;
        httpResponse = null;
        try
        {
            var creator = (ModelState.IsValid)? 
                new OkResponseCreator(root) as IHttpResponseCreator: 
                new BadReqeuestResponseCreator(ApplicationSettings.HttpBadRequestErrorMessage);

            var abstractHttpResponse = new ResponseContext(creator).CreateHttpResponse();
            httpResponse = Request.CreateResponse(abstractHttpResponse.StatusCode, abstractHttpResponse);

            success = true;
        }
        catch
        {
            success = false;
        }

        return success;
    }
}

Aucun commentaire:

Enregistrer un commentaire