Unit Test ASP.NET Web API controller with fake HTTPContext

前端 未结 2 1512
抹茶落季
抹茶落季 2020-12-10 01:04

I\'m using the following approach to upload files through ASP.NET Web API controllers.

[System.Web.Http.HttpPost]
public HttpResponseMessage UploadFile()
{
          


        
2条回答
  •  -上瘾入骨i
    2020-12-10 01:27

    Since you have no control over those classes why not wrap/abstract the functionality behind one do control

    IRequestService request;
    
    [HttpPost]
    public HttpResponseMessage UploadFile() {
        HttpResponseMessage response;
    
        try {
            int id = 0;
            int? qId = null;
            if (int.TryParse(request.GetFormValue("id"), out id)) {
                qId = id;
            }
    
            var file = request.GetFile(0);
    
            int filePursuitId = bl.UploadFile(qId, file);
        } catch (Exception ex) {
            //...
        }
    
        return response;
    }
    

    Where request is one of your custom defined types IRequestService

    public interface IRequestService {
        string GetFormValue(string key);
        HttpPostedFileBase GetFile(int index);
        //...other functionality you may need to abstract
    }
    

    and can be implemented like this to be injected into your controller

    public class RequestService : IRequestService {
    
        public string GetFormValue(string key) {
            return HttpContext.Current.Request.Form[key];
        }
    
        public HttpPostedFileBase GetFile(int index) {
            return new HttpPostedFileWrapper(HttpContext.Current.Request.Files[index]);
        }
    }
    

    in your unit test

    var requestMock = new Mock();
    //you then setup the mock to return your fake data
    //...
    //and then inject it into your controller
    var controller = new MyController(requestMock.Object);
    //Act
    response = controller.UploadFile();
    

提交回复
热议问题