我剛開始一項新工作,並且我被要求做的第一件事之一是爲代碼庫建立單元測試(我現在工作的公司致力於自動化測試但他們主要進行集成測試,並且構建需要永遠完成)。不能讓Rhino Mocks返回正確的類型
所以一切都很好的開始,我就開始在這裏和那裏打破依賴關係,並開始寫孤立的單元測試,但現在我在與犀牛的問題嘲笑不能夠處理以下情況:
//authenticationSessionManager is injected through the constructor.
var authSession = authenticationSessionManager.GetSession(new Guid(authentication.SessionId));
((IExpirableSessionContext)authSession).InvalidateEnabled = false;
GetSession方法返回的類型是SessionContext,正如您所看到的,它會被轉換到IExpirableSessionContext接口中。
還有一個ExpirableSessionContext對象,它繼承自SessionContext並實現IExpirableSessionContext接口。
會話對象存儲和檢索顯示在下面的代碼片段的方式:
private readonly Dictionary<Guid, SessionContext<TContent>> Sessions= new Dictionary<Guid, SessionContext<TContent>>();
public override SessionContext<TContent> GetSession(Guid sessionId)
{
var session = base.GetSession(sessionId);
if (session != null)
{
((IExpirableSessionContext)session).ResetTimeout();
}
return session;
}
public override SessionContext<TContent> CreateSession(TContent content)
{
var session = new ExpirableSessionContext<TContent>(content, SessionTimeoutMilliseconds, new TimerCallback(InvalidateSession));
Sessions.Add(session.Id, session);
return session;
}
現在我的問題是,當我嘲笑調用getSession,即使我告訴犀牛嘲笑返回的ExpirableSessionContext < ...>對象,測試會在它被輸入到IExpirableSession接口的行上拋出一個異常,這裏是我測試中的代碼(我知道我使用的是舊語法,請在這一頁上與我聯繫):
Mocks = new MockRepository();
IAuthenticationSessionManager AuthenticationSessionMock;
AuthenticationSessionMock = Mocks.DynamicMock<IAuthenticationSessionManager>();
var stationAgentManager = new StationAgentManager(AuthenticationSessionMock);
var authenticationSession = new ExpirableSessionContext<AuthenticationSessionContent>(new AuthenticationSessionContent(AnyUserName, AnyPassword), 1, null);
using (Mocks.Record())
{
Expect.Call(AuthenticationSessionMock.GetSession(Guid.NewGuid())).IgnoreArguments().Return(authenticationSession);
}
using (Mocks.Playback())
{
var result = stationAgentManager.StartDeploymentSession(anyAuthenticationCookie);
Assert.IsFalse(((IExpirableSessionContext)authenticationSession).InvalidateEnabled);
}
我認爲轉換失敗是有意義的,因爲該方法返回一個不同類型的對象,並且生產代碼工作,因爲會話被創建爲正確的類型並存儲在字典中,該字典是代碼,因爲它被嘲笑,測試永遠不會運行。
如何設置此測試以正確運行?
感謝您提供任何幫助。