如何测试接收FormData的C#WebApi post方法

时间:2017-06-27 00:28:09

标签: c# unit-testing asp.net-web-api2 multipartform-data

我有一个带有post方法的控制器:

public HttpResponseMessage Post()
        {            
            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            var name = System.Web.HttpContext.Current.Request.Form.Get("Name");
            var description = System.Web.HttpContext.Current.Request.Form.Get("Description");
            HttpPostedFile theFile = null;
            if (files.Count > 0)
            {
                theFile = files[0];
            }
            var categoryPost = new CategoryPostDto()
            {
                Id = 1,
                Name = name,
                Description = description,
                Logo = theFile
            };
            //var categoryService = new CategoryServiceFake();
            try
            {
                //var newCategory = categoryService.AddCategory(name, description, files);
                var newCategory = categoryService.AddCategory(categoryPost);
                return Request.CreateResponse(HttpStatusCode.OK, newCategory);
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

在这个控制器上,我从前端收到一个formData,它可以工作,但我想做的是unitesting我试图根据这篇文章生成上下文:

Unitesting a post method

我在单元测试中实现了这个实现,但它没有工作:

[TestMethod]
        public void TestMethod1()
        {
            //arrange
            var formData = new NameValueCollection { { "Name", "Hotels" } };
            var request = new Mock<HttpRequestBase>();
            request.SetupGet(r => r.Form).Returns(formData);
            var context = new Mock<HttpContextBase>();
            context.SetupGet(c => c.Request).Returns(request.Object);

            var myController = new CategoriesController();
            myController.Request = new HttpRequestMessage();
            myController.Configuration = new HttpConfiguration();
            myController.ControllerContext = new ControllerContext(context.Object, new RouteData(), myController);
            //act
            var response = myController.Post();

            CategoryPostDto categoryPostDto;
            Assert.IsTrue(response.TryGetContentValue<CategoryPostDto>(out categoryPostDto));
            Assert.AreEqual("Hotels", categoryPostDto.Name);            
        }

0 个答案:

没有答案