使用假 HTTPContext 单元测试 ASP.NET Web API 控制器 [英] Unit Test ASP.NET Web API controller with fake HTTPContext
问题描述
我使用以下方法通过 ASP.NET Web API 控制器上传文件.
I'm using the following approach to upload files through 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;
}
在我的单元测试中,我在调用 UploadFile
操作之前手动创建了一个 HTTPContext
类:
In my unit tests I've created an HTTPContext
class manually before calling the UploadFile
action:
var request = new HttpRequest("", "http://localhost", "");
var context = new HttpContext(request, new HttpResponse(new StringWriter()));
HttpContext.Current = context;
response = controller.UploadFile();
不幸的是,我无法向 Form
集合添加自定义值,因为它是只读的.我也无法更改 Files
集合.
Unfortunately, I wasn't able to add custom values to the Form
collection, since it's read-only. Also I couldn't change the Files
collection.
是否有任何方法可以将自定义值添加到 Request
的 Form
和 Files
属性以添加所需的数据(id 和文件内容)) 在单元测试期间?
Is there any way 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?
推荐答案
使用一些模拟框架,例如 Moq反而.使用您需要的任何数据创建一个模拟 HttpRequestBase 和模拟 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"]);
}
}
}
这篇关于使用假 HTTPContext 单元测试 ASP.NET Web API 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!