使用 TestControllerBuilder 返回特定的 UserHostAddress
我正在使用 MvcContrib 和 TestControllerBuilder 为我的控制器编写测试。
我正在为我的错误处理控制器编写测试,如下所示:
public JsonResult HttpError()
{
Exception ex = null;
try
{
ex = (Exception)HttpContext.Application[Request.UserHostAddress.ToString()];
}
catch
{
}
if( ex != null )
{
return Json( new ErrorViewModel() { Message = ex.Message, Source = ex.Source, StackTrace = ex.StackTrace, Type = ex.GetType().Name}, JsonRequestBehavior.AllowGet );
}
else
{
return Json( new ErrorViewModel() { Message = "An error has occured." }, JsonRequestBehavior.AllowGet );
}
}
基本上,我的全局错误处理将最后一个异常放入应用程序存储中,并且该控制器尝试将其拉出,将其转换为 Json,然后返回它(我们是以 Json 形式返回所有内容,因为这些方法仅作为 Web 服务被调用)。
为了充分测试这一点,我需要 UserHostAddress 包含一些可预测的内容,但 TestControllerBuilder 设置的对象将该属性保留为空。
我怎样才能做到这一点?我不确定如何在我的测试中使其发挥作用。
I am using MvcContrib and the TestControllerBuilder to write tests for my controller.
I am writing the tests for my Error Handling Controller that looks like this:
public JsonResult HttpError()
{
Exception ex = null;
try
{
ex = (Exception)HttpContext.Application[Request.UserHostAddress.ToString()];
}
catch
{
}
if( ex != null )
{
return Json( new ErrorViewModel() { Message = ex.Message, Source = ex.Source, StackTrace = ex.StackTrace, Type = ex.GetType().Name}, JsonRequestBehavior.AllowGet );
}
else
{
return Json( new ErrorViewModel() { Message = "An error has occured." }, JsonRequestBehavior.AllowGet );
}
}
Basically, my global error handling puts the last exception into the Application store and this controller tries to pull it back out, convert it to Json, and return it (we are returning everything as Json because these methods are only getting called as Web Services).
To fully test this, I need for UserHostAddress to contain something predictable, but the objects setup by TestControllerBuilder leave that property null.
How can I make this work? I'm not sure how I can make this work in my test.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
TestControllerBuilder 使用 Rhino.Mocks 来模拟 HttpContext。知道了这一点,您可以将 Request 对象放回到“记录”模式并存根响应:
在初始化控制器之后、方法调用之前执行此操作。
TestControllerBuilder uses Rhino.Mocks for mocking the HttpContext. Knowing this, you could put the Request object back into "record" mode and stub out a response:
Do this after you've initialized the controller, but before your method call.