Messagebox and Unit testing

后端 未结 4 1669
再見小時候
再見小時候 2020-12-28 21:37

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 he

4条回答
  •  [愿得一人]
    2020-12-28 22:15

    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...", ...);
            }
        }
    }
    

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

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

提交回复
热议问题