How to use Rhino Mocks to Mock an HttpContext.Application

我是研究僧i 提交于 2019-11-30 04:02:13

Without delving too deeply, this looks mostly correct.

The Application property is virtual on HttpContextBase, so you should be able to set up a return value for it from Rhino -- Assuming you're mocking HttpContextBase as Scott Hanselmanns post does.

Some possible causes, which are really just guesses from lack of information:

  • Did you set up returns for controllerToTest.ControllerContext?
  • Did you set up a return for that objects HttpContext property?
  • Did you set up a return for that objects Application property?

The reason I ask is that typically when you do expectation setups, you already have references to the objects that will be called as part of your test, so you wouldn't do a property chain like you do with your controllerToTest.ControllerContext.HttpContext. Expect() call.

Edit:

I think I see the problem, and I think it's with this part:

Expect(ctx => ctx.Application[Globals.GlobalsKey])

I think you're assuming that indexers work the same as properties, when they don't. What you really need to do is set up an expectation on your appState object to receive a call to the Item property, like this:

// setup expectations -- assumes some of the expectations and mocks 
// the from original question
mockHttpBase.Expect(ctx => ctx.Application).Return(appState);
appState.Expect(ctx => ctx.Item(Globals.GlobalsKey)).Return(tmpAppGlobals);

// run the test

you could use the below for Moq. It took me awhile how to mock the HttpApplication, and the appState.Object is the return method duh!

public static HttpContextBase FakeHttpContext()
    {
        var context = new Mock<HttpContextBase>();
        var request = new Mock<HttpRequestBase>();
        var response = new Mock<HttpResponseBase>();
        var session = new FakeHttpSessionState();
        var server = new Mock<HttpServerUtilityBase>();
        var appState = new Mock<HttpApplicationStateBase>();

        context.Setup(ctx => ctx.Request).Returns(request.Object);
        context.Setup(ctx => ctx.Response).Returns(response.Object);
        context.Setup(ctx => ctx.Session).Returns(session);
        context.Setup(ctx => ctx.Server).Returns(server.Object);
        context.Setup(ctx => ctx.Application).Returns(appState.Object);

        //emulate session (HttpContext.Current.Session) 
        var contx = new HttpContext(new MyApp.NUnit.Tests.Fakes.FakeHttpWorkerRequest());
        contx.Items["AspSession"] = CreateSession();

        HttpContext.Current = contx;

        return context.Object;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!