消息框和单元测试 [英] Messagebox and Unit testing

查看:135
本文介绍了消息框和单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到从脱钩我的逻辑提示消息框这样我就可以正常单元测试的最佳方法。现在,我在想,如果这将是不够的,如果我只是做了一个单独的辅助类(C#),我可以在以后存根我的消息框。例如:

I'm trying to find the best way to uncouple messageboxes from my logic so I can properly unittest it. Now I was wondering if it would be enough if I just made a seperate helper class (C#) which I can stub later for my messagebox. For instance:

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(...)。使用布尔表演,我可以启用或测试期间禁用它。

Then everytime I'd need to use a messagebox i'd just use messageboxHelper/msgBoxAlg(...) instead of messagebox.show(...). Using the bool show I could enable or disable it during testing.

我只是想知道,如果这是正确的方式。我的意思是,有更简单的或更好的方法来正确地做到这一点?我不能只在沟提示消息,他们接力重要信息给用户(是否要关闭此窗口?YES / NO等)。它也可能只是我没有使用正确的软件工程,我就从我的bussinesslogic更脱钩我提示消息框?

I'm just wondering if this is the "right way". By which I mean, is there an easier or better way to do this properly? I can't just ditch the messageboxes, they relay "vital" info to the user ("Do you want to close this windows?" YES/NO etc.). It could also just be I'm not using proper software engineering, and I should decouple my messageboxes from my bussinesslogic more?

推荐答案

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

Yes, it is right way. But instead of static class, you should implement IDialogService and inject it into classes that should display dialogs:

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的你应该注入的 IDialogService 的,而不是真正的模仿对象。

During testing the SomeClass you should inject mock object of the IDialogService instead of real one.

如果你需要测试更多的UI逻辑,可考虑使用 MVVM 模式。

If you need to test more UI logic, consider to use MVVM pattern.

这篇关于消息框和单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆