为模拟的复合部分设置结果
我们尝试使用 RhinoMocks 模拟 MVC 3 应用程序的 HttpContext 看起来像这样:
HttpContextBase context = mocks.StrictMock<HttpContextBase>();
HttpRequestBase request = mocks.PartialMock<HttpRequestBase>();
IPrincipal user = mocks.StrictMock<IPrincipal>();
HttpCookieCollection cookies = new HttpCookieCollection();
IIdentity identity = mocks.StrictMock<IIdentity>();
HttpResponseBase response = mocks.PartialMock<HttpResponseBase>();
SetupResult.For(response.Cookies).Return(cookies);
SetupResult.For(context.User).Return(user);
SetupResult.For(user.Identity).Return(identity);
SetupResult.For(context.Request).Return(request);
SetupResult.For(context.Response).Return(response);
mocks.Replay(context);
在我的测试中,我需要对用户进行身份验证,因此我添加了以下内容:
var identity = context.User.Identity;
mocks.BackToRecord(identity);
SetupResult.For(identity.IsAuthenticated).Return(true).Repeat.Any();
mocks.Replay(identity);
但这会导致 “IIdentity.get_IsAuthenticated(); 的结果已设置。” 要抛出的异常。
为什么?我需要做什么才能使经过身份验证的可设置在我的测试中?
We try to mock a HttpContext of an MVC 3 application using RhinoMocks
Looks like this:
HttpContextBase context = mocks.StrictMock<HttpContextBase>();
HttpRequestBase request = mocks.PartialMock<HttpRequestBase>();
IPrincipal user = mocks.StrictMock<IPrincipal>();
HttpCookieCollection cookies = new HttpCookieCollection();
IIdentity identity = mocks.StrictMock<IIdentity>();
HttpResponseBase response = mocks.PartialMock<HttpResponseBase>();
SetupResult.For(response.Cookies).Return(cookies);
SetupResult.For(context.User).Return(user);
SetupResult.For(user.Identity).Return(identity);
SetupResult.For(context.Request).Return(request);
SetupResult.For(context.Response).Return(response);
mocks.Replay(context);
In my test I need the user to be authenticated so I added following:
var identity = context.User.Identity;
mocks.BackToRecord(identity);
SetupResult.For(identity.IsAuthenticated).Return(true).Repeat.Any();
mocks.Replay(identity);
This however results in a
"The result for IIdentity.get_IsAuthenticated(); has already been setup."
exception to be thrown.
Why? What do I need to do to make the authenticated settable in my tests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经很长时间没有使用记录/重播语义与 AAA(安排/行动/断言)语法了,但尝试仅在身份模拟上执行
SetupResult
:新答案< /strong>
去掉
.Repeat.Any()
。我认为既然这是一个属性,你只需要设置返回值即可。 Rhino.Mocks 将始终返回该值——您不需要告诉它重复。我做了一个快速测试,并得到了与您相同的错误,但是当我删除.Repeat.Any()
后,它就起作用了。It's been a long time since I used the record/replay semantics vs. the AAA (Arrange/Act/Assert) syntax, but try doing the
SetupResult
on just the identity mock:NEW ANSWER
Get rid of the
.Repeat.Any()
. I think since this is a property, you just need to set the return value. Rhino.Mocks will always return that value -- you don't need to tell it to repeat. I did a quick test and was getting the same error you got, but as soon as I removed the.Repeat.Any()
, it worked.