我在 Blazor 项目中使用 Radzen,并且决定学习使用 bUnit 编写测试。然而,我遇到了困难。
有时,随机 id 会分配给 Radzen 组件生成的元素。当我将测试结果与我期望的结果进行比较时,这会导致不匹配。
例如,我有一个名为 DefaultProcessingTemplate.razor 的组件:
@using ClientProcessing.Library
@inject IJSRuntime JsRuntime
//@inject DialogService DialogService
@if (ClientProcessor as IDataProcessing is not null)
{
<RadzenRow>
<RadzenHeading Size="H2" Text="Reporting"></RadzenHeading>
</RadzenRow>
<RadzenRow Gap=".5rem" class="rz-mb-6">
<RadzenButton Click="OpenReportingRunDialog" ButtonStyle="ButtonStyle.Primary" Text="Run"></RadzenButton>
<RadzenButton Click="OpenReportingDownloadDialog" ButtonStyle="ButtonStyle.Primary" Text="Download"></RadzenButton>
</RadzenRow>
}
else
{
// code ...
}
@code {
private DialogOptions defaultDialogOptions = new DialogOptions { CloseDialogOnEsc = true, Width = "900px" };
[Parameter]
public IDataProcessing ClientProcessor { get; set; }
protected override void OnInitialized()
{
// ... code
}
private async Task OpenReportingRunDialog()
{
var parameters = new Dictionary<string, object>()
{
{ "CommDate", ClientProcessor.GetCurrMo() },
{ "Reporting", ClientProcessor }
};
//await DialogService.OpenAsync<ReportingRun>("Run", parameters, defaultDialogOptions);
}
private async Task OpenReportingDownloadDialog()
{
var reporting = ClientProcessor as IReporting;
var parameters = new Dictionary<string, object> { { "FilePaths", reporting.GetReportPaths() } };
var options = new DialogOptions
{
CloseDialogOnEsc = true,
Width = "1200px"
};
//await DialogService.OpenAsync<DownloadFiles>("Download", parameters, options);
}
}
我想测试一下,如果
ClientProcessor
参数不为空,则DefaultProcessingTemplate
组件包含<RadzenHeading Size="H2" Text="Processing"></RadzenHeading>
元素。以下是我想出的最好的测试方法。
默认处理模板测试.razor:
@using ClientProcessing.BlazorServer.Components.Shared
@using ClientProcessing.Library
@using Moq
@using Radzen.Blazor
@inherits TestContext
@code {
private readonly Mock<IDataProcessing> _mockDatabaseProcessing = new Mock<IDataProcessing>();
[Fact]
public void HasSection()
{
var cut = Render(@<DefaultProcessingTemplate ClientProcessor="_mockDatabaseProcessing.Object" />);
cut.Find("h2").MarkupMatches(@<RadzenHeading Size="H2" Text="Reporting"></RadzenHeading>);
}
}
由于这些随机生成的 id,测试失败了:
Message:
Bunit.HtmlEqualException : HTML comparison failed.
The following errors were found:
1: The values of the attributes at h2(0)[id] are different.
Actual HTML:
<h2 class="rz-heading" id="4KjgjHwknU" >Reporting</h2>
Expected HTML:
<h2 class="rz-heading" id="cHelqcQDgU" >Reporting</h2>
如何为使用 Radzen 的 Blazor 组件编写测试?有没有方便的方法来做到这一点?
Bunit 允许您自定义比较标记的方式,请参阅 https://bunit.dev/docs/verification/semantic-html-comparison.html
但是,在这种情况下,您实际上是在测试我不建议的 Radzons 组件,将您的测试紧密耦合到 Radzons 实现细节(其组件生成的标记)而不是其公共 api 表面。
您可能想在这里测试的是,您的被测组件有一个预期的子组件(
RadzenHeading
),并且预期的参数已传递给它,例如:
var rh = cut.FindComponent<RadzenHeading>();
Assert.Equal("H2", rh.Instance.Size);
Assert.Equal("Heading", rh.Instance.Text);