我有一个密封类单例 Foo 及其方法:
public string GetFolderPath(FooFolder folder)
{
IBoo boo = this.GetBoo();
return boo.GetFolderPath(folder);
}
并希望使用 GetFolderPath 方法为名为 FindFile 的方法编写测试,如下所示:
[TestMethod]
public void FindFile()
{
string expectedPath = Path.Combine(Path.GetTempPath(), "TestPath");
using (ShimsContext.Create())
{
Fakes.ShimFoo.AllInstances.GetFolderPathFolder
= () => { return "C:\\...\\Temp"; };
}
string actualPath = WorkflowHelper.FindFile("TestPath");
Assert.AreEqual(expectedPath, actualPath);
}
问题是我遇到了以下编译错误:
委托(delegate)不接受 0 个参数
在类似的问题中 How to shim OpenFileDialog.ShowDialog method问题是这样解决的:
[TestMethod]
public void SomeTest()
{
using (var context = ShimsContext.Create())
{
Nullable<bool> b2 = true;
ShimCommonDialog.AllInstances.ShowDialog = (x) => b2;
var sut = new Sut();
var r = sut.SomeMethod();
Assert.IsTrue(r);
}
}
所以我尝试了同样的...根据 GetFolderPath 是一个带有 1 个参数的方法...
下一个问题是我遇到以下编译错误:
委托(delegate)不接受 1 个参数
所以我的问题是:
是否可以填充密封类,尤其是单例?如果是这样,我的错误是什么?
谢谢你的期待
请您参考如下方法:
请注意,ShimsContext 生命周期内分配的所有 shim 都将在 ShimsContext 被释放后销毁。
在您的示例中,您在绑定(bind) ShimsContext 生命周期的 using block 之外调用 WorkflowHelper.FindFile,因此 Foo.GetFolderPath 的填充定义 不再有效,对 FindFile 的调用将使用原始方法定义。
只需将您的方法调用移到 using block 中,它就会起作用:
using (ShimsContext.Create())
{
Fakes.ShimFoo.AllInstances.GetFolderPathFolder = ...; // your lambda expression
string actualPath = WorkflowHelper.FindFile("TestPath");
}
Assert.AreEqual(expectedPath, actualPath);
