对于控制器上下文的单元测试空引用异常 [英] Unit Testing null reference exception for controller context

查看:201
本文介绍了对于控制器上下文的单元测试空引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试控制器,我想改变它的背景,所以我可以在申请文件发布消息,我的code看起来像:

  System.Drawing.Image对象图像= System.Drawing.Image.FromFile(.. \\\\ .. \\\\ \\\\图片UploadFileTest.jpg);VAR器=新System.Drawing.ImageConverter();
字节[] = byteContent(字节[])converter.ConvertTo(图像的typeof(字节[]));
VAR内容=新ByteArrayContent(byteContent);
content.Headers.Add(内容处置,表单数据);
VAR controllerContext =新HttpControllerContext()
{
    请求=新的Htt prequestMessage(){内容=新MultipartContent(){内容}}
};
VAR控制器=新ActionsController();
controller.ControllerContext = controllerContext;
字符串fileUrl = controller.UploadFile();

不过,我在我的线控器得到NullReferenceExcetion:

  VAR请求= HttpContext.Current.Request;


解决方案

在生产中,IIS服务器的主机应用程序填充 HttpContext.Current 为每个请求。(具体上下文)

在您的UT没有什么是填充 HttpContext.Current 来的一个实例,这就是问题所在。

您必须初始化 HttpContext.Current

  HttpContext.Current =新的HttpContext(新的Htt prequest(,http://blabla.com,),
                                      新的Htt presponse(新的StringWriter()));

还有一件事(只是你要假的HttpContext 情况); 的HttpContext 密封类,你将无法使用代理工具,如犀牛-嘲笑 / 起订量。你必须使用code编织工具,如 MsFakes / TypeMock隔离 ...

I'm trying to test controller and I want to change it's context so I can post message with file in request My code looks like that:

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

However I get NullReferenceExcetion in my controller on line:

var request = HttpContext.Current.Request;

解决方案

In production, the IIS Server which host your application populates HttpContext.Current for each request.(specific context)

In your UT nothing was populate HttpContext.Current to an instance, this is the problem.

You have to initialize HttpContext.Current:

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

One more thing(just in case you are going to fake HttpContext); HttpContext is a sealed class, you won't be able to fake it using proxy tools like Rhino-Mocks / Moq. You'll have to use code weaving tools like MsFakes / TypeMock Isolator...

这篇关于对于控制器上下文的单元测试空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆