如何实现IDialogService来包装Messsage.Box以进行测试
本文关键字:Box Messsage 测试 包装 何实现 实现 IDialogService | 更新日期: 2023-09-27 18:31:07
我需要对Nunit进行一些单元测试,发现我对MessageBox.Show的调用妨碍了我。我正在查看IDialogService并尝试实现它。
这是界面。
namespace Exec.Core.Interfaces
{
public interface IDialogService
{
DialogResult ShowMessageBox(string text, string caption, MessageBoxButtons buttons);
DialogResult ShowMessageBox(string text, string caption);
DialogResult ShowMessageBox(string text);
}
}
这是实现。
namespace Exec.Core
{
public interface IDialogService
{
}
public DialogResult ShowMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
return MessageBox.Show( text, caption, buttons, icon);
}
public DialogResult ShowMessageBox(string text, string caption, MessageBoxButtons buttons)
{
return MessageBox.Show(text, caption, buttons);
}
}
}
在这里,它进入了一个班级
namespace JobExec.Modules.Tasks
{
private IDialogService dialogService;
public partial class frmTask : form
{
private void Load_Form( object sender, EventArgs e)
{
dialogService = new DialogService();
other stuff
}
}
}
我对目标的理解是,我试图围绕Message.Box包装一个类,以便我可以用NSubstitute来模拟它
。我能让它工作的唯一方法是load_form事件中的行dialogService = new DialogService();
。
似乎我需要将private IDialogService dialogService;
添加到每个类的顶部,dialogService = new DialogService();
添加到每个类的每个构造函数中。
这似乎很臭。
我的方法正确吗?
谢谢
科林
将接口的实例传递到窗体构造函数中更为常见。
关键是,您不能在表单中调用new DialogService()
,因为这会剥夺将其替换为实际上不显示 MessageBox 的版本的机会。
然后,当涉及到单元测试时,您可以传入不显示 MessageBox 的IDialogService
的模拟实现。
这是依赖注入。有些人使用 DI 框架,但您不需要为此提供框架。如果你有一个包含大量依赖项的大型对象图,那么经过一些设置后,使用框架会使事情更容易管理。
当然,还有其他方法:你可以说有某种静态的DialogServiceFactory,你可以在运行时更改它,然后你从每个模块引用它,甚至是像服务定位器这样的东西。
请注意,您需要保留设计器支持的默认构造函数,并从注入构造函数调用它。