如何模拟和设置 MudBlazor.IDialogService - 使用 Moq 的对话结果?

问题描述 投票:0回答:1

我正在使用 Bunit、Xunit 和 Moq 为 blazor webAssembly 编写单元测试。

我想模拟 MudBlazor.IDialogService

测试文件

var mockDialogService = new Mock<IDialogService>();

var ctx = new Bunit.TestContext();
           ctx.Services.AddScoped<IDialogService, DialogService>();

var cut = new Participant(
           mockDialogService.Object
);

在 .razor 方法中

var parameters = new DialogParameters();
parameters.Add("ContentText", "Please assign coordinator before schedule a meeting.");
parameters.Add("ButtonText", "Ok");
parameters.Add("Color", Color.Primary);

var options = new DialogOptions() { MaxWidth = MaxWidth.Medium };

var dialogresult = DialogService.Show<ConfirmationDialog>("Warning", parameters, options);  
// when debugging in test mode dialogresult is null how can I setup this?

var result = await dialogresult.Result;
.net moq blazor-webassembly mudblazor bunit
1个回答
0
投票

你需要模拟代表你的对话的

IDialogReference

var confirmationDialogReference = new Mock<IDialogReference>();
confirmationDialogReference.SetupGet(x => x.Result).Returns(Task.FromResult(DialogResult.Ok<object>(new object())));

var mockDialogService = new Mock<IDialogService>();
mockDialogService.Setup(x => x.ShowAsync<ConfirmationDialog>(It.IsAny<string>(), It.IsAny<DialogParameters>(), It.IsAny<DialogOptions>()))
            .ReturnsAsync(confirmationDialogReference.Object);

然后将模拟服务添加到 DI 容器中:

ctx.Services.AddScoped(typeof(IDialogService), mockDialogService.Object);
© www.soinside.com 2019 - 2024. All rights reserved.