用于模拟 OpenFileDialog 的选项
本文关键字:选项 OpenFileDialog 模拟 用于 | 更新日期: 2023-09-27 18:37:25
我试图接近100%的代码覆盖率,我有兴趣嘲笑OpenFileDialog。从一些研究中,似乎一个好的答案是创建一个 IFileDialogService,就像打开文件对话框 MVVM 中的以下代码一样:
public interface IOpenFileService
{
string FileName { get; }
bool OpenFileDialog()
// Many other methods and properties of OpenFileDialog here...
}
但是,这意味着我必须实现 OpenFileDialog 的所有属性和方法,并简单地将它们作为调用真正 OpenFileDialog 的属性和方法的传递。
我希望做一些事情,比如有一个MockContainer和一个RealContainer,每个都会返回他们的OpenFileDialog版本:
public class MockContainer
{
IOpenFileDialog FileDialog { get { return new MockOpenFileDialog(); } }
}
public class RealContainer
{
IOpenFileDialog FileDialog { get { return new OpenFileDialog(); } }
}
但是,我不能这样做,因为它们没有实现通用接口。如果我能够采用这种方法,我就不需要在 IOpenFileService 中创建传递方法来实现 OpenFileDialog 所需的一切。每个容器只会返回调用方可以使用的对话框。
有没有办法使这种方法起作用,或者IOpenFileService真的是这样做的方法吗?
注意:我知道模拟框架。我想今天快速实现一些东西,并且还不想花时间学习模拟框架。我想我自己可以很容易地嘲笑它。
这是适配器模式的纯案例
你非常接近(你需要的最后一步是从某个基本接口继承MockContainer
和RealContainer
- 像这样:
public class MockContainer : IOpenFileDialog
{
IOpenFileDialog FileDialog { get { return this; } }
}
public class RealContainer : IOpenFileDialog
{
IOpenFileDialog FileDialog { get { return this; } }
}
然后将它们模拟为IOpenFileDialog
对象