单元测试ASP.NET使用伪造的Web API控制器的HttpContext

编程入门 行业动态 更新时间:2024-10-24 01:48:25
本文介绍了单元测试ASP.NET使用伪造的Web API控制器的HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用的另一个方法通过的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

本文发布于:2023-11-14 13:49:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587388.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   单元测试   ASP   Web   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!