Sample code for unit testing api controllers

后端 未结 4 879
遥遥无期
遥遥无期 2021-02-04 03:44

Is there an sample code that shows unit testing a controller that inherits from the api controller? I am trying to unit test a POST but it is failing. I believe I need to set up

4条回答
  •  情深已故
    2021-02-04 04:23

    I've created a general solution for calling some action and getting HttpResponseMessage as Dictionary which is very convenient for usage.

    First some extension for the dictionary:

    public static class DictionaryExtensions
    {
        public static void AddRange(this Dictionary source,
                                          Dictionary collection) 
        {
            if (collection == null)
            {
                throw new NullReferenceException("Collection is null");
            }
    
            foreach (var item in collection)
            {
                source.Add(item.Key, item.Value);
            }
        }
    }
    

    Now request creating part:

    public class RequestCreator
    {
        protected static void FirstPart(ApiController controller,
                                        HttpMethod method,String actionUrl)
        {
            // Creating basic request message with message type and requesting 
            // url example : 'http://www.someHostName/UrlPath/'
            controller.Request = new HttpRequestMessage(method, actionUrl);
    
            // Adding configuration for request
            controller.Request.Properties.
              Add(HttpPropertyKeys.HttpConfigurationKey,new HttpConfiguration());                                         
        }
    
        protected static Dictionary SecondPart
                                                     (HttpResponseMessage response)
        {
            // Adding basic response content to dictionary
            var resultCollection = new Dictionary
            {
                {"StatusCode",response.StatusCode},
                {"Headers",response.Headers},
                {"Version",response.Version},
                {"RequestMessage",response.RequestMessage},
                {"ReasonPhrase",response.ReasonPhrase},
                {"IsSuccessStatusCode",response.IsSuccessStatusCode}
            };
    
            var responseContent = response.Content;
            // If response has content then parsing it and 
            // getting content properties
            if (null != responseContent)
            {
                var resultMessageString = response.Content.
                                                   ReadAsStringAsync().Result;
                resultCollection.AddRange((new JavaScriptSerializer()).
                                           DeserializeObject(resultMessageString) 
                                                   as Dictionary);
            }
    
    
            return resultCollection;
        }       
    }
    

    And finally response message to dictionary converter class:

    public class HttpResponseModelGetter : RequestCreator
    {
        public Dictionary
                     GetActionResponse(ApiController controller,HttpMethod method,
                              String actionUrl,Func callBack)
        {
            FirstPart(controller, method, actionUrl);
            var response = callBack();
            return SecondPart(response);
        }
    }
    
    public class HttpResponseModelGetter : RequestCreator
    {
        public Dictionary 
                 GetActionResponse(ApiController controller,HttpMethod method,
                    String actionUrl,Func callBack,T param) 
        {
            FirstPart(controller, method, actionUrl);
            var response = callBack(param);
            return SecondPart(response);
        }
    }
    
    public class HttpResponseModelGetter : RequestCreator
    {
        public Dictionary 
            GetActionResponse(ApiController controller,HttpMethod method, 
                 String actionUrl,Func callBack,
                 T1 param1,T2 param2)
    
    
        {
            FirstPart(controller, method, actionUrl);
            var response = callBack(param1,param2);
            return SecondPart(response);
        }
    } 
    //and so on...
    

    and usage :

    var responseGetter = new HttpResponseModelGetter();
    var result = responseGetter.GetActionResponse(controller,HttpMethod.Get,
                        "http://localhost/Project/api/MyControllerApi/SomeApiMethod",
                                                  controller.SomeApiMethod);
    
    Boolean isComplete = Boolean.Parse(result["isComplete"].ToString());
    

提交回复
热议问题