【发布时间】:2011-07-20 20:30:21
【问题描述】:
我刚开始一份新工作,我被要求做的第一件事就是为代码库构建单元测试(我现在工作的公司致力于自动化测试,但他们主要进行集成测试和构建需要永远完成)。
所以一切都开始得很顺利,我开始在这里和那里打破依赖关系并开始编写独立的单元测试,但现在我遇到了 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接口。
session对象的存储和检索方式如下sn-p所示:
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 的调用时,即使我告诉 rhino 模拟返回一个 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);
}
我认为强制转换失败是有道理的,因为该方法返回了一种不同类型的对象,并且生产代码有效,因为会话被创建为正确的类型并存储在字典中,这是测试永远不会运行的代码,因为它被嘲笑了。
如何设置此测试以正确运行?
感谢您提供的任何帮助。
【问题讨论】:
标签: rhino-mocks