单元测试:硬依赖 MessageBox.Show()
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;
}
}
What ways can the SampleConfirmationDialog be unit tested? The SampleConfirmationDialog would be exercised via acceptance tests, however how could we unit test it, seeing as MessageBox is not abstract and no matching interface?
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能,它在当前状态下是不可测试的。对于这个特定的类,对其进行单元测试也没有任何价值……它只是内置框架功能的一个轻量级包装,因此您要做的就是测试框架。
如果您绝对必须测试它,则 IConfirmationDialog 接口应该具有另一个可以在单元测试中模拟的依赖项。
You can't, it's untestable in it's current state. For this particular class, there is also no value in unit testing it ... it is but a light wrapper around a built-in framework feature, so all you'd be doing is testing the framework.
If you absolutely must test it, the IConfirmationDialog interface should have another dependency that you can mock up in the unit test.
您应该研究 Typemock,这是一个商业模拟框架,它允许您使用 .NET 性能分析库对此类情况进行单元测试。请参阅他们的网站了解更多信息。
You should look into Typemock, a commercial mocking framework that lets you unit test these kinds of situations by using the .NET performance profiling libraries. See their website for more information.
我认为在那个级别停止测试是可以的。您与
IConfirmationDialog
的交互比验证MessageBox.Show
是否确实被调用更重要。由于这是一个界面并且很容易模拟,因此我认为您已经很好地了解了。I think it's OK to stop testing it at that level. Your interaction with
IConfirmationDialog
is more important than verifying thatMessageBox.Show
is actually getting called. Since that is an interface and is easily mockable, I think you are pretty well covered.