I want to mock the User property of an HttpContext. I'm using Scott Hanselmans MVCHelper class and RhinoMocks.
I have a unit test that contains code, like this:
...
MockIdentity fakeId = new MockIdentity("TEST_USER", "Windows", true);
MockPrincipal fakeUser = new MockPrincipal(null, fakeId);
using (mocks.Record())
{
Expect.Call(fakeHttpContext.User).Return(fakeUser);
}
...
My MockIdentity and MockPrincipal classes are mocks conforming to IIdentity and IPrincipal, respectively.
I get an error when running the unit test that reports:
System.NotImplementedException : The method or operation is not implemented. at System.Web.HttpContextBase.get_User()
This is happening when I'm trying to set the expectation for the User property.
I understand that the httpContextBase has a getter and setter that aren't implemented but I thought that Rhino would handle this when mocking.
Does this mean that I have to derive from the HttpContextbase and override the property for my mock object. It seems odd.
Other users have had this issue and it's reported here: http://www.mail-archive.com/rhinomocks@googlegroups.com/msg00546.html
To mock the user property, you can do this:
var httpContext = MockRepository.GenerateStub<HttpContextBase>();
httpContext.Stub(x=>x.User).Return(yourFakePrincipalHere);
var controllerContext = new ControllerContext(httpContext, ....);
var controller = new HomeController();
controller.ControllerContext = controllerContext;
(this uses the new RM 3.5 api, if you're doing it w/ record/replay then:
using(mocks.Record)
{
_httpContext = _mocks.DynamicMock<HttpContextBase>();
SetupResult.For(_httpContext.User).Return(...);
}
using(mocks.PlayBack())
{
....
}