我正在尝试找到将消息框与我的逻辑分离的最佳方法,以便我可以正确地对其进行单元测试。现在我想知道如果我只制作一个单独的帮助器类 (C#) 是否足够,我可以稍后为我的消息框 stub 。例如:
static class messageBoxHelper
{
public static void msgBoxAlg(string message, string title, MessageBoxButtons buttons, MessageBoxIcon icons, bool show)
{
if (show)
{
MessageBox.Show(message, title, buttons, icons);
}
}
然后每次我需要使用消息框时,我只使用 messageboxHelper/msgBoxAlg(...) 而不是 messagebox.show(...)。使用 bool show 我可以在测试期间启用或禁用它。
我只是想知道这是否是“正确的方式”。我的意思是,是否有更简单或更好的方法来正确执行此操作?我不能只是放弃消息框,它们会将“重要”信息传递给用户(“你想关闭这个窗口吗?”是/否等)。也可能只是我没有使用适当的软件工程,我应该更多地将我的消息框与我的业务逻辑分离?
最佳答案
是的,这是正确的方法。但是你应该实现 IDialogService
而不是静态类,并将它注入(inject)到应该显示对话框的类中:
public interface IDialogService
{
void ShowMessageBox(...);
...
}
public class SomeClass
{
private IDialogService dialogService;
public SomeClass(IDialogService dialogService)
{
this.dialogService = dialogService;
}
public void SomeLogic()
{
...
if (ok)
{
this.dialogService.ShowMessageBox("SUCCESS", ...);
}
else
{
this.dialogService.ShowMessageBox("SHIT HAPPENS...", ...);
}
}
}
在测试 SomeClass
期间,您应该注入(inject) IDialogService
的模拟对象而不是真实对象。
如果需要测试更多的UI逻辑,可以考虑使用MVVM模式。
关于c# - 消息框和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8560865/