控制器上下文的单元测试空引用异常

问题描述 投票:0回答:3

我正在尝试测试控制器,我想更改它的上下文,以便我可以在请求中使用文件发布消息我的代码如下所示:

System.Drawing.Image image = System.Drawing.Image.FromFile("..\\..\\Images\\UploadFileTest.jpg");

var converter = new System.Drawing.ImageConverter();
byte[] byteContent = (byte[]) converter.ConvertTo(image,typeof(byte[]));
var content = new ByteArrayContent(byteContent);
content.Headers.Add("Content-Disposition", "form-data");
var controllerContext = new HttpControllerContext()
{
    Request = new HttpRequestMessage() { Content = new MultipartContent() { content } }
};
var controller = new ActionsController();
controller.ControllerContext = controllerContext;
string fileUrl = controller.UploadFile();

但是我在我的控制器中在线得到 NullReferenceExcetion:

var request = HttpContext.Current.Request;
c# unit-testing asp.net-web-api
3个回答
2
投票

在生产中,托管应用程序的 IIS 服务器会为每个请求填充

HttpContext.Current
。(特定上下文)

在您的 UT 中,没有任何内容填充到实例中,这就是问题所在。


你必须初始化

HttpContext.Current

:


HttpContext.Current

还有一件事(以防万一你要假装
HttpContext.Current = new HttpContext(new HttpRequest("", "http://blabla.com", ""), new HttpResponse(new StringWriter()));

);

HttpContext
是一个
HttpContext
类,您将无法使用
sealed
/
Rhino-Mocks
等代理工具来伪造它。您必须使用代码编织工具,例如
Moq
/
MsFakes
...
    


0
投票
Typemock Isolator

来伪造 HttpContext

TypeMock Isolator

这些行构成了所谓的递归假,这意味着调用任何成员及其成员等不会导致异常,它将返回默认值或另一个递归假。此外,它还解决了通常因伪造 HttpContext 而出现的单例问题。

如果要设置特定值,只需使用 Isolate.WhenCalled(..).Return() 方法。例如:

var fake = Isolate.Fake.AllInstances<HttpContext>(); Isolate.Fake.StaticMethods<HttpContext>();

希望有帮助!


0
投票
我认为这样做的最好方法是在 Request 对象上编写一个扩展方法,然后在该方法中像这样发挥你的魔力,

Isolate.WhenCalled(() => HttpContext.Current.Request).WillReturn(new HttpRequest("", "http://smth.com", ""));
然后,您可以调用请求对象上的内容并访问您的数据。

© www.soinside.com 2019 - 2024. All rights reserved.