我有以下签名的扩展方法(在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
}
而且我想
[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);
}
}
当我运行这个测试,我得到:使用MSTest的和Rhino.Mocks(V3.4)与测试
System.InvalidOperationException
:Previous方法
IBuildServer.CreateBuildAgentSpec("TeamProjectName");
需要一个返回值或异常抛出。
这显然是调用真正的扩展方法而不是测试实现。我的下一个倾向是尝试:
Expect.Call(BuildServerExtensions.GetEnabledBuildAgents(buildServer, TeamProjectName))
.Return(null);
然后我注意到我对Rhino.Mocks截取这个的期望很可能是错误的。
问题是:我如何消除这种依赖关系并使Select方法可测试?
请注意,扩展方法和BuildAgentSelector类是在同一个程序集中,我宁愿避免改变这个或不得不转向除了扩展方法之外的东西,尽管另一个模拟框架是我会考虑如果我知道它会处理这个情况。