在 .net 中使用 Moq 模拟对话框后获取对话框中的消息

本文关键字:对话框 获取 消息 Moq net 模拟 | 更新日期: 2023-09-27 17:56:04

>我正在对对话框进行单元测试,在测试用例中,对话框可能会根据测试用例以不同的消息启动。

对话框代码:

uiService.ShowMessage(StudioViewName.MainWindow, "No cell selected.", this.resourceManager.GetResourceString(StudioResourceManagerName.StudioResourceManager, "IDC_WinshuttleStudio"), MessageBoxButton.OK, MessageBoxImage.Error);

我这样嘲笑它:UIServicemock.Setup(u=>u.ShowMessage(It.IsAny<int>(),It.IsAny<string>(),It.IsAny<string>(),It.IsAny<MessageBoxButton>(),It.IsAny<MessageBoxImage>()))

现在,我想检查对话框中的消息,或者在单元测试用例中验证是否仅弹出特定的消息承载框。

在 .net 中使用 Moq 模拟对话框后获取对话框中的消息

您可以使用回调来断言值与预期匹配。

UIServicemock
    .Setup(u => u.ShowMessage(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(),
        It.IsAny<MessageBoxButton>(), It.IsAny<MessageBoxImage>()))
    .Callback<int, string, string, MessageBoxButton, MessageBoxImage>((window, message, error, button, image) => {
        Assert.That(message, Is.EqualTo("No cell selected"));
        Assert.That(window, Is.EqualTo(StudioViewName.MainWindow));
    });

或者,您可以使用与特定参数匹配的 It 匹配器,如下所示:

UIServicemock
    .Setup(u => u.ShowMessage(
        It.Is<int>(s => s == StudioViewName.MainWindow),
        It.IsIn<string>("No cell selected"),
        It.IsAny<string>(),
        It.IsAny<MessageBoxButton>(),
        It.IsAny<MessageBoxImage>()));

我通常发现第一种方法更灵活,但它更冗长。

使用 Verify

string expectedResourceString = /* whatever you expect */;
UIServicemock.Verify(u => u.ShowMessage(StudioViewName.MainWindow, 
                                        "No cell selected",
                                        expectedResourceString,
                                        MessageBoxButton.OK, 
                                        MessageBoxImage.Error));

更清楚您要测试的内容。 如果您不在乎价值,我们It.IsAny代替它。