消息框和单元测试

Ent*_*mer 9 c# unit-testing messagebox

我正在尝试找到从我的逻辑中解开消息框的最佳方法,以便我可以正确地对其进行单元测试.现在我想知道如果我只是制作了一个单独的帮助类(C#)就足够了,我可以稍后将其存储到我的消息框中.例如:

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

然后,每当我需要使用消息框时,我只使用messageboxHelper/msgBoxAlg(...)而不是messagebox.show(...).使用bool show我可以在测试期间启用或禁用它.

我只是想知道这是否是"正确的方法".我的意思是,是否有更简单或更好的方法来做到这一点?我不能只丢弃消息框,他们将"重要"信息传递给用户("你想关闭这个窗口吗?"是/否等).它也可能只是我没有使用适当的软件工程,我应该将我的消息框与我的bussinesslogic分开更多?

Ser*_*huk 32

是的,这是正确的方式.但是应该实现IDialogService并将其注入应该显示对话框的类中而不是静态类:

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

在测试期间,SomeClass您应该注入模拟对象IDialogService而不是真实对象.

如果需要测试更多UI逻辑,请考虑使用MVVM模式.