模拟Web API HTTPResponseMessage C#单元测试

时间:2017-04-17 01:44:46

标签: c# unit-testing asp.net-web-api tdd moq

我想为下面的方法创建一个单元测试方法,它接收文件上传“文本文件”数据并解析它,我尝试使用Moq并创建了一个方法,但我仍然很困惑这个概念,我需要一个示例代码,我已经阅读了很多stackover flow问题,但它完全适用于Controllers而不是Web API 使用的方法

// Enable both Get and Post so that our jquery call can send data, and get a status
        [HttpGet]
        [HttpPost]
        public HttpResponseMessage Upload()
        {
            // Get a reference to the file that our jQuery sent. Even if multiple files, they will
            // all be their own request and be the 0 index

            if (HttpContext.Current.Request.Files.Count>0)
            {
                HttpPostedFile file = HttpContext.Current.Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    try
                    {

                        var extension = Path.GetExtension(file.FileName);
                        if (!IsFileFormatSupported(extension))
                        {
                            var objectSerialized = SerializeData(GetError( GlobalResources.NotSupportedFileExtension));
                            return BadResponse(objectSerialized);
                        }
                        var path = SaveFileGetPath(file);
                        var result = GetPaySlips(path);
                        var SerializedData = SerializeData(result);
                        return OkResponse(SerializedData);
                    }
                    catch (System.Exception exception)
                    {
                        var SerializedData = SerializeData(GetError( GlobalResources.CouldNotReadFile + " " + exception.Message));
                        return BadResponse(SerializedData);
                    }
                }
                else
                {
                    var SerializedData = SerializeData(GetError(file.FileName + " " +  GlobalResources.FileisCorrupt));
                    return BadResponse(SerializedData);
                }
            }else
            {
                var SerializedData = SerializeData(GetError( GlobalResources.FileisCorrupt));
                return BadResponse(SerializedData);
            }
        }

到目前为止我所做的代码

    var FileUploadCtrl = new UploadController();
    Mock<HttpRequestMessage> cc = new Mock<HttpRequestMessage>();
    UTF8Encoding enc = new UTF8Encoding();

    // Mock<HttpPostedFileBase> file1 = new Mock<HttpPostedFileBase>();
    //file1.Expect(f=>f.InputStream).Returns(file1.Object.InputStream);
    //cc.Expect(ctx => ctx.Content).Returns(new retur);
   // cc.Expect(ctx => ctx.Content).Returns();
    var content = new ByteArrayContent( /* bytes in the file */ );
    content.Headers.Add("Content-Disposition", "form-data");
    var controllerContext = new HttpControllerContext
    {
        Request = new HttpRequestMessage
        {
            Content = new MultipartContent { content }
        }
    };

    //file1.Expect(d => d.FileName).Returns("FileTest.csv");
    //file1.Expect(d => d.InputStream).Returns(new HttpResponseMessage(HttpStatusCode.OK)));
    var config = new HttpConfiguration();
    //var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/upload");
    var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
    var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "FileUpload" } });



    FileUploadCtrl.ControllerContext = new HttpControllerContext(config, routeData, cc.Object);
    var r = FileUploadCtrl.Upload();
    Assert.IsInstanceOfType(r, typeof(HttpResponseMessage));

0 个答案:

没有答案