簡體   English   中英

為模擬的復合部分設置結果

[英]Set up a result for a composite part of a mock

我們嘗試使用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();的結果已設置。” 拋出異常。

為什么? 我需要做些什么才能使測試中的身份驗證可設置表?

自從我使用記錄/重播語義與AAA(Arrange / Act / Assert)語法以來已有很長時間了,但是嘗試SetupResult身份模擬執行SetupResult

mocks.BackToRecord(identity);
SetupResult.For(identity.IsAuthenticated).Return(true).Repeat.Any();
mocks.Replay(identity);

新答案

擺脫.Repeat.Any() 我認為由於這是一個屬性,因此您只需要設置返回值即可。 Rhino.Mocks將始終返回該值-您無需告訴它重復。 我進行了快速測試,並收到與您相同的錯誤,但是,一旦我刪除了.Repeat.Any() ,它就起作用了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM