我正在对 Blazor 应用程序进行单元测试。我得到一个 ElementNotFoundException。我认为造成这种情况的原因是 index.razor 页面中的 if 语句。见下面的代码:
<div class="row">
<div class="col-12">
@if ((challenges != null) && (challenges.Count > 0))
{
<MultiStepComponent Id="MultiStepContainer" Challenges="@challenges">
<div class="row p-3">
<div class="col-6" id="challengeContainer">
@foreach(var c in challenges)
{
<MultiStepNavigation Name="@c.Title">
<h1>@c.Title</h1>
<img class="float-left" src="@c.ImagePath" width="200" />
@foreach(var sentence in c.Description)
{
<p>@sentence</p>
}
</MultiStepNavigation>
}
</div>
<div class="col-6">
<textarea rows="26" cols="120" @bind="input" id="input"></textarea>
<button class="btn" id="runBtn" @onclick="RunAsync">Run</button>
<br />
<textarea rows="10" cols="120" id="output" readonly>@((MarkupString)Output)</textarea>
</div>
</div>
</MultiStepComponent>
}
</div>
</div>
这个页面后面的代码(index.razor.cs)有如下初始化代码:
protected override async Task OnInitializedAsync()
{
jsonRepository = new JSONChallengeRepository();
challenges = await jsonRepository.GetChallengesAsync();
}
此页面的测试在这里:
[Test]
public async Task Compile_code_Success()
{
_codingChallengeService.Setup(c => c.SendInputToCompilerAsync("50+50")).ReturnsAsync("100");
_testContext.Services.AddScoped(x => _codingChallengeService.Object);
var razorComponent = _testContext.RenderComponent<Index>();
razorComponent.Instance.challenges = GetChallenges();
if ((razorComponent.Instance.challenges != null) && (razorComponent.Instance.challenges.Count > 0))
{
var runBtn = razorComponent.FindAll("button").FirstOrDefault(b => b.OuterHtml.Contains("Run"));
var input = razorComponent.Find("#input");
input.Change("50+50");
runBtn.Click();
var outputArea = razorComponent.Find("#output");
var outputAreaText = outputArea.TextContent;
Assert.AreEqual("100", outputAreaText);
}
Assert.IsNotNull(razorComponent.Instance.challenges);
}
#input 丢失了..为什么?
提前致谢!