【问题标题】:Unit Testing: hard dependency MessageBox.Show()单元测试:硬依赖 MessageBox.Show()
【发布时间】:2010-05-20 21:15:51
【问题描述】:

可以通过哪些方式对 SampleConfirmationDialog 进行单元测试? SampleConfirmationDialog 将通过验收测试来执行,但是我们如何对它进行单元测试,因为 MessageBox 不是抽象的并且没有匹配的接口?

public interface IConfirmationDialog
{
    /// <summary>
    /// Confirms the dialog with the user
    /// </summary>
    /// <returns>True if confirmed, false if not, null if cancelled</returns>
    bool? Confirm();
}


/// <summary>
/// Implementation of a confirmation dialog
/// </summary>
public class SampleConfirmationDialog : IConfirmationDialog
{
    /// <summary>
    /// Confirms the dialog with the user
    /// </summary>
    /// <returns>True if confirmed, false if not, null if cancelled</returns>
    public bool? Confirm()
    {
        return MessageBox.Show("do operation x?", "title", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
    }
}

【问题讨论】:

    标签: wpf unit-testing tdd nunit mbunit


    【解决方案1】:

    你不能,它在当前状态下是不可测试的。对于这个特定的类,对它进行单元测试也没有任何价值……它只是对内置框架特性的轻包装,所以你要做的就是测试框架。

    如果你绝对必须测试它,IConfirmationDialog 接口应该有另一个依赖项,你可以在单元测试中模拟它。

    【讨论】:

    • 换句话说,您想测试SampleConfirmationDialog,而不是MessageBox 类。你可以抽象一个IConfirmationProvider,其中一个实现可能使用MessageBox,你可以测试Confirm()调用IConfirmationProvider.GetConfirmation(),但这对你没有帮助——在某种程度上你会遇到无法测试MessageBox.
    • 是的,谢谢。这个一直困扰着我。但你们俩都是对的。
    【解决方案2】:

    您应该研究 Typemock,这是一个商业模拟框架,可让您使用 .NET 性能分析库对这些情况进行单元测试。请参阅their website 了解更多信息。

    【讨论】:

      【解决方案3】:

      我认为停止在该级别进行测试是可以的。您与IConfirmationDialog 的交互比验证MessageBox.Show 是否实际被调用更重要。由于这是一个界面并且很容易模拟,我认为你已经很好地覆盖了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-27
        • 2021-06-19
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多