.net 如何使用Moq模拟和设置MudBlazor.IDialogService - dialogresult?

ubby3x7f  于 2023-05-19  发布在  .NET
关注(0)|答案(1)|浏览(138)

我正在使用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
);

剃刀法

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;
jogvjijk

jogvjijk1#

您需要模拟代表对话框的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);

相关问题