3

我正在使用伪造的 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;

}

ps:我用的是起订量

更新

我的天啊!!我不敢相信!2个多小时才弄清楚问题是对错误的MVC dll的引用。我在我的主应用程序中引用了 System.Web.Mvc 2.0,但在另一个项目中引用了 System.Web.Mvc 1.0。为此事道歉!

4

1 回答 1

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"]);
    }
}
于 2010-10-04T18:54:01.627 回答