如何在WPF中测试MessageBox?

问题描述

我要进行一些单元测试,而我在MessageBox方面苦苦挣扎。我有一个MessageBox,它在我的代码中显示一个文本和一个“确定”按钮。当我尝试对包含MessageBox.Show("Text")的方法进行单元测试时,它也会在单元测试中弹出,并且我必须单击“确定”才能通过,这很不好。

有人知道如何解决吗?我想我需要某种伪造此MessageBox并单击“确定”的代码,但是我不知道该怎么做。我是一名初级程序员,所以请尽可能轻松地进行解释;),并高兴地提供一些代码示例。

这是我的MessageBox代码:

public void GetPopUpWithErrorMessage()
{
   MessageBox.Show("Error Message","text",MessageBoxButton.OK);
}

修改 我刚刚意识到项目中使用了Fluent Assertions。有谁知道如何在测试代码中实现它?是否与@thatguy显示的方式相同?

解决方法

您必须创建一个实现可以在测试中模拟的接口的服务。

public interface IMessageBoxService
{
   void ShowMessageBox(string title,string message);
}

public class MessageBoxService : IMessageBoxService
{
   public void ShowMessageBox(string title,string message)
   {
      MessageBox.Show(message,title,MessageBoxButton.OK);
   }
}

在使用它的类中,您将通过其接口传递此服务,例如在构造函数中,因此该类仅知道其合同,而没有其实现。

public class MyClass
{
   private IMessageBoxService _messageBoxService;

   public MyClass(IMessageBoxService messageBoxService)
   {
      _messageBoxService = messageBoxService;
   }

   public void GetPopUpWithErrorMessage()
   {
      _messageBoxService.ShowMessageBox("text","Error Message");
   }
}

在测试类中,您需要使用类似Moq的模拟框架,该框架从接口创建模拟对象,该接口只是一个存根,可用于为您所使用的任何方法或属性注入行为在测试中使用。

在此示例中,使用 NUnit Moq messageBoxService被创建为实现IMessageBoxService接口的模拟对象。除非您指定它们应该执行的操作或通过Setup返回的方法,否则所有方法均不执行任何操作,但这是另一个主题。最后一行显示了如何检查测试过程中是否调用了模拟的另一个方法。

[TestFixture]
public class MyClassTest
{
   [Test]
   public void MyTest()
   {
      var messageBoxService = Mock.Of<IMessageBoxService>();
      var myClass = new MyClass(messageBoxService);

      // ...your test code.

      // Checks if the "ShowMessageBox" method in the service was called with any strings
      Mock.Get(messageBoxService).Verify(mock => mock.ShowMessageBox(It.IsAny<string>(),It.IsAny<string>()));
   }
}

创建服务和接口不仅对模拟有用,而且对于分离视图和逻辑也非常有用,因为您可以将消息框的调用提取到服务中,该服务的实现隐藏在接口后面。而且,您可以通过构造函数轻松实现依赖注入。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...