我正在使用伪造的HttpContext(最后提供的代码),可能我遗漏了一些东西,因为我无法访问TempData集合(SetFakeControllerContext方法的第四行)。每次我尝试时都会收到此错误消息:
'controller.TempData'引发了'System.AccessViolationException'类型的异常
调用FakeHttpContext的代码是:
public static void SetFakeControllerContext(this Controller controller)
{
HttpContextBase httpContext = FakeHttpContext(string.Empty);
var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
controller.ControllerContext = context;
controller.TempData = new TempDataDictionary(); //This is not necessary! It was just a test!!!!
}
有人知道我做错了吗?
public static HttpContextBase FakeHttpContext(string username){
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
user.Setup(ctx => ctx.Identity).Returns(identity.Object);
if (!string.IsNullOrEmpty(username))
{
identity.Setup(id => id.IsAuthenticated).Returns(true);
identity.Setup(id => id.Name).Returns(username);
}
else
{
identity.Setup(id => id.IsAuthenticated).Returns(false);
identity.Setup(id => id.Name).Returns(string.Empty);
}
context.Setup(ctx => ctx.Response.Cache).Returns(CreateCachePolicy());
return context.Object;
}
P.s。:我正在使用Moq
更新:
OMG !!我不相信!超过2个小时才发现问题是对错误的MVC dll的引用。我在我的主应用程序中引用了System.Web.Mvc 2.0,但在另一个项目中引用了System.Web.Mvc 1.0。对此抱歉!
答案 0 :(得分:4)
问题肯定在其他地方。您甚至不需要在单元测试中将TempData
属性初始化为新字典。以下程序运行正常:
public class HomeController: Controller
{
public ActionResult Index()
{
TempData["foo"] = "bar";
return View();
}
}
class Program
{
static void Main()
{
var controller = new HomeController();
controller.Index();
Console.WriteLine(controller.TempData["foo"]);
}
}