我使用的另一个方法通过的ASP.NET Web API控制器上传文件。
I'm using the next approach to upload files through the ASP.NET Web API controllers.
[System.Web.Http.HttpPost] public HttpResponseMessage UploadFile() { HttpResponseMessage response; try { int id = 0; int? qId = null; if (int.TryParse(HttpContext.Current.Request.Form["id"], out id)) { qId = id; } var file = HttpContext.Current.Request.Files[0]; int filePursuitId = bl.UploadFile(qId, file); } catch (Exception ex) { } return response; }在我的单元测试我创建HttpContext类调用UploadFile行动之前手动:
In my unit tests I've created HTTPContext class manually before calling UploadFile action:
var request = new HttpRequest("", "localhost", ""); var context = new HttpContext(request, new HttpResponse(new StringWriter())); HttpContext.Current = context; response = controller.UploadFile();不幸的是,我没能自定义值添加到Form集合,因为它是只读的。此外,我无法改变的文件集合。
Unfortunately, I wasn't able to add custom values to the Form collection, since it's read-only. Also I couldn't change Files collection.
时它自定义值添加到窗体和请求的文件属性设置为单元测试过程中添加需要的数据(ID和文件内容)的方式?
Is it any ways to add custom values to the Form and Files properties of the Request to add needed data (id and file content) during the unit test?
感谢您!
推荐答案使用像一些模拟框架起订量代替。创建一个模拟的Htt prequestBase和模拟HttpContextBase您所需要的任何数据,并将它们设置在控制器上。
Use some mocking framework like Moq instead. Create a mock HttpRequestBase and mock HttpContextBase with whatever data you need and set them on the controller.
using Moq; using NUnit.Framework; using SharpTestsEx; namespace StackOverflowExample.Moq { public class MyController : Controller { public string UploadFile() { return Request.Form["id"]; } } [TestFixture] public class WebApiTests { [Test] public void Should_return_form_data() { //arrange var formData = new NameValueCollection {{"id", "test"}}; 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 MyController(); myController.ControllerContext = new ControllerContext(context.Object, new RouteData(), myController); //act var result = myController.UploadFile(); //assert result.Should().Be.EqualTo(formData["id"]); } } }更多推荐
单元测试ASP.NET使用伪造的Web API控制器的HttpContext
发布评论