gpt4 book ai didi

c# - Controller 上下文的单元测试空引用异常

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:23 27 4
gpt4 key购买 nike

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

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();

但是我在线上在我的 Controller 中得到了 NullReferenceExcetion:

var request = HttpContext.Current.Request;

最佳答案

在生产中,托管您的应用程序的 IIS 服务器填充 HttpContext.Current对于每个请求。(特定上下文)

在您的 UT 中没有填充任何内容 HttpContext.Current举个例子,这就是问题所在。

你必须初始化HttpContext.Current :

HttpContext.Current = new HttpContext(new HttpRequest("", "http://blabla.com", ""),
new HttpResponse(new StringWriter()));

还有一件事(以防万一你要伪造 HttpContext ); HttpContextsealed类,您将无法使用 Rhino-Mocks 等代理工具伪造它/Moq .您将不得不使用代码编织工具,例如 MsFakes/TypeMock Isolator ...

关于c# - Controller 上下文的单元测试空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33342324/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com