我有一个扩展方法,签名如下(在BuildServerExtensions类中):
public static IEnumerable<BuildAgent> GetEnabledBuildAgents(
this IBuildServer buildServer,
string teamProjectName)
{
// omitted agrument validation and irrelevant code
var buildAgentSpec = buildServer.CreateBuildAgentSpec(teamProjectName);
}
另一种调用第一个方法的方法(在BuildAgentSelector类中):
public BuildAgent Select(IBuildServer buildServer, string teamProjectName)
{
// omitted argument validation
IEnumerable<BuildAgent> serverBuildAgents =
buildServer.GetEnabledBuildAgents(teamProjectName);
// omitted - test doesn't get this far
}
我正在尝试使用MSTest和Rhino.Mocks(v3.4)进行测试,具体如下:
[TestMethod]
public void SelectReturnsNullOnNullBuildAgents()
{
Mocks = new MockRepository();
IBuildServer buildServer = Mocks.CreateMock<IBuildServer>();
BuildAgentSelector buildAgentSelector = new BuildAgentSelector();
using (Mocks.Record())
{
Expect.Call(buildServer.GetEnabledBuildAgents(TeamProjectName)).Return(null);
}
using (Mocks.Playback())
{
BuildAgent buildAgent = buildAgentSelector.Select(buildServer, TeamProjectName);
Assert.IsNull(buildAgent);
}
}
当我运行这个测试时,我得到了以下错误信息:
很明显,这里调用的是真正的扩展方法而不是测试实现。我的下一个想法是尝试:
System.InvalidOperationException
:之前的方法
IBuildServer.CreateBuildAgentSpec("TeamProjectName");
需要返回值或抛出异常。
Expect.Call(BuildServerExtensions.GetEnabledBuildAgents(buildServer, TeamProjectName))
.Return(null);
然后我注意到,我对Rhino.Mocks拦截它的期望可能是不合适的。
问题是:我如何消除这种依赖关系,并使Select方法可测试?
请注意,扩展方法和BuildAgentSelector类位于同一个程序集中,我希望避免更改此内容或使用除扩展方法以外的其他内容,尽管如果我知道另一个模拟框架可以处理此情况,我也会考虑使用它。