【问题标题】:Options to Mock OpenFileDialog模拟 OpenFileDialog 的选项
【发布时间】:2012-06-17 17:16:22
【问题描述】:

我正在尝试接近 100% 的代码覆盖率,并且我对模拟 OpenFileDialog 很感兴趣。从一些研究来看,一个好的答案似乎是创建一个 IFileDialogService,就像来自 Open File Dialog 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 真的可以做到吗?

注意:我了解模拟框架。我今天想快速实现一些东西,还不想花时间学习一个模拟框架。我想我可以很容易地自己模拟它。

【问题讨论】:

  • 是的。我想过子类化它,但不能......

标签: c# mocking


【解决方案1】:

这是Adapter pattern的纯粹案例

你非常接近(你需要的最后一步是从一些基本接口继承 MockContainerRealContainer - 像这样:

public class MockContainer : IOpenFileDialog 
{
    IOpenFileDialog FileDialog { get { return this; } }
}

public class RealContainer : IOpenFileDialog 
{
    IOpenFileDialog FileDialog { get { return this; } }
}

然后将它们模拟为IOpenFileDialog 对象

【讨论】:

  • 在这个实现中,我不是必须实现 RealContainer 中的所有 OpenFileDialog 方法吗?
  • @BobHorn 你不必这样做。将 IOpenFileDialog 重构为您需要的属性和函数。
  • 对。我需要实现我需要的所有属性和方法,并且只需在真实对话框中调用相同的属性/方法。虽然我希望避免这样做,但似乎这是唯一的方法。谢谢。
  • 最难模拟OpenFileDialog 的部分是这个Dialog 是Win32 纯窗口,而OpenFileDialog 只是它的一个包装器。可能你能找到一种方法,但我在互联网上搜索过,没有自动/模拟方法来插入文件名并在没有自动化帮助的情况下单击“确定”按钮。这导致包装自动化的类(FindWindow、Invoke on button 等)。 OpenFile、SaveFile 和 FontDialog 很难模拟对话框并且几乎总是需要一个包装器:(
猜你喜欢
  • 2019-12-30
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
相关资源
最近更新 更多