用于Web API单元测试的模拟Request.files [0]

时间:2017-04-20 11:44:03

标签: unit-testing asp.net-web-api rhino-mocks

我想对我的Web API控制器进行单元测试。我有一个问题,我的一个动作方法[post]需要来自Request对象的值,以获取控制器名称。我正在使用Rhino模拟来支持我的单元测试

这是我的控制器代码:

 public int CustomerUpdate()
        {
            var localhost = HttpContext.Current.Request.Url.Authority;
            HttpPostedFile file = HttpContext.Current.Request.Files[0];
            var formData = HttpContext.Current.Request.Form["FormData"];
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            var customer = json_serializer.Deserialize<Customer>(formData);
            if (file.FileName != null)
            {
                string fileName = customer.CustomerName.Trim() + "_" + file.FileName;
                var filePath = HttpContext.Current.Server.MapPath(Constants.FileUploadImagePath + fileName);
                file.SaveAs(filePath);
                customer.Logo = fileName;
            }
            return _iCustomerService.Update(customer);
        }

这是我的单元测试方法

 public void CustomerController_UpdateUnitTest()
        {
            var customers = new Customer() { CustomerName = "Enterprise" };

            HttpContextBase mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
            HttpRequestBase mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
            mockHttpContext.Stub(x => x.Request).Return(mockRequest);

            var filesMock = MockRepository.GenerateMock<HttpFileCollectionBase>();
            var fileMock = MockRepository.GenerateMock<HttpPostedFileBase>();


            filesMock.Stub(x => x[0]).Return(fileMock);
            mockRequest.Stub(x => x.Files).Return(filesMock);
            var t = mockHttpContext.Request;


            var mockRepository = MockRepository.GenerateMock<ICustomerService>();
            mockRepository.Stub(x => x.Update(new Customer())).IgnoreArguments().Return(1);
            _customerController = new CustomerController(mockRepository)

            // _customerController.Stub(c => c.Request).Return(request);

            var result = _customerController.CustomerUpdate();
            //Assert.IsNotNull(forms);
            Assert.IsNotNull(result);

        }

我无法模仿任何人都可以帮我用给定参数模拟这个方法

0 个答案:

没有答案