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

Wpf 单元测试:硬依赖MessageBox.Show(),wpf,unit-testing,tdd,nunit,mbunit,Wpf,Unit Testing,Tdd,Nunit,Mbunit,SampleConfirmationDialog可以通过什么方式进行单元测试?SampleConfirmationDialog将通过验收测试来执行,但是我们如何对其进行单元测试,因为MessageBox不是抽象的,也没有匹配的接口 public interface IConfirmationDialog { /// <summary> /// Confirms the dialog with the user /// </summary>

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;
    }
}
公共界面图标确认对话框
{
/// 
///与用户确认对话框
/// 
///如果确认,则为True;如果未确认,则为false;如果取消,则为null
bool?Confirm();
}
/// 
///确认对话框的实现
/// 
公共类SampleConfirmationDialog:IConfirmationDialog
{
/// 
///与用户确认对话框
/// 
///如果确认,则为True;如果未确认,则为false;如果取消,则为null
公共布尔?确认()
{
返回MessageBox.Show(“执行操作x?”,“标题”,MessageBoxButton.YesNo,MessageBoxImage.Question)=MessageBoxResult.Yes;
}
}

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


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

您应该研究Typemock,一个商业模拟框架,它允许您使用.NET性能分析库对这些情况进行单元测试。有关更多信息,请参阅。

我认为停止在该级别测试是可以的。与
iconficationdialog
的交互比验证
MessageBox.Show是否实际被调用更重要。因为这是一个接口,很容易模仿,所以我认为您已经做得很好了。

换句话说,您要测试的是
SampleConfirmationDialog
,而不是
MessageBox
类。您可以抽象一个
IConfimationProvider
,其中一个实现可以使用
MessageBox
,您可以测试
Confirm()
调用
IConfimationProvider.GetConfirmation()
,但这对您没有帮助——在某种程度上,您会遇到不稳定的
MessageBox。
是的,谢谢。这个一直困扰着我。但你们都是对的。