我正在使用 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;
你需要模拟代表你的对话的
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);