I'm having an issue mocking something in
MVC.NET. I made a post on the
ASP.NET forums which you can reference here:
http://forums.asp.net/t/1232755.aspx.
My goal is to mock out the Authentication stuff and test my
Controller. The method I'm testing on the controller looks like this:
public void Index()
{
if (!User.Identity.IsAuthenticated)
RedirectToAction("Step1");
}
I want to mock out the User.Identity.IsAuthenticated and just test the
RedirectToAction. I use this is a few other places so getting this
simple action working would be helpful elsewhere.
My simple test looks like so:
[Test]
public void CanMockUserObject()
{
RegisterController controller = new RegisterController();
MockRepository mocks = new MockRepository();
IPrincipal principal;
using (mocks.Record())
{
IIdentity identity = mocks.CreateMock<IIdentity>();
SetupResult.For(identity.IsAuthenticated).Return(true);
principal = mocks.CreateMock<IPrincipal>();
SetupResult.For(principal.Identity).Return(identity);
mocks.SetFakeControllerContext(controller);
// Problem HERE
SetupResult.For(controller.HttpContext.User).Return(principal);
}
using (mocks.Playback())
{
Assert.IsNotNull(controller.HttpContext.User);
}
}
I'm using Scott Hanselman's MvcMockHelpers to mock the HttpContext
available here:
http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx
The problems is on the
SetupResult.For(controller.HttpContext.User).Return(principal); line.
When it gets here I get the following exception:
TestCase
'WSDOT.Tests.Controllers.RegisterControllerTests.CanMockUserObject'
failed: System.InvalidOperationException : Invalid call, the last call
has been used or no call has been made (make sure that you are calling
a virtual (C#) / Overridable (VB) method).
at Rhino.Mocks.LastCall.GetOptions[T]()
at Rhino.Mocks.SetupResult.For[T](T ignored)
at
WSDOT.Tests.Controllers.RegisterControllerTests.CanMockUserObject() in
D:\Workspaces\WSDOT_CommuteLog\WSDOT.Tests\Controllers
\RegisterControllerTests.cs:line 28 D:\Workspaces\WSDOT_CommuteLog
\WSDOT.Tests\Controllers\RegisterControllerTests.cs 28
What am I doing wrong, or what do I need to do to mock the call to
IsAuthenticated out?
Jack