单元测试:硬依赖MessageBox.Show()

Sea*_*n B 2 wpf tdd mbunit nunit unit-testing

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*nez 5

你不能,它在当前状态下是不可测试的.对于这个特定的类,单元测试也没有价值......它只是一个内置框架功能的轻量级包装器,所以你要做的就是测试框架.

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

  • 换句话说,您想要测试`SampleConfirmationDialog`,而不是`MessageBox`类.你可以抽象一个`IConfirmationProvider`,其中一个实现可以使用`MessageBox`,你可以测试`Confirm()`调用`IConfirmationProvider.GetConfirmation()`,但这对你没有帮助 - 在某种程度上你会碰到那个不可测试的`MessageBox (3认同)