C#Xamarin UITest-如何断言元素是否存在以及文本是否正确

时间:2018-04-13 18:48:54

标签: c# xamarin ui-testing

场景:

在C#中编写自动化测试(即Xamarin UITest,Nunit等)时,我想断言元素是否存在以及该元素的文本是否正确。 (即元素X存在且看到的文字是Y)

Intellisense告诉我,Assert是一个选项,但我似乎无法找到完成此任务的方法。

我可以做类似" app.Flash(e => e.Id(" TheId"));" ,这将向人类用户显示元素闪烁,但我想在其中断言,并向用户显示正确的文本。

1 个答案:

答案 0 :(得分:2)

这是一个等待页面出现的示例,测试某个元素是否可用,然后测试该元素是否包含某个值。

单一资产测试案例

[Test]
public void StackOverEntry()
{
    // Wait for the page to appear, test to see if some static (always present) element is available
    AppResult[] results = app.WaitForElement(c => c.Marked("Welcome to Xamarin Forms!"));

    var elementQuery = app.Query(c => c.Marked("SOEntry"));
    var elementAvailable = elementQuery.Any();
    string elementValue = "";
    if (elementAvailable)
        elementValue = elementQuery.First().Text;

    Assert.IsTrue(elementAvailable && elementValue == "StackOverflow", "Not available and/or correct");
}

个人断言测试用例

[Test]
public void StackOverEntry()
{
    // Wait for the page to appear, test to see if some static (always present) element is available
    AppResult[] results = app.WaitForElement(c => c.Marked("Welcome to Xamarin Forms!"));
    // Test of the element is on the page (via AutomationId in this class)
    Assert.NotNull(app.Query(c => c.Marked("SOEntry")).FirstOrDefault());
    // Test the the element contains the proper value
    Assert.AreEqual("StackOverflow", app.Query(c => c.Marked("SOEntry")).First().Text);
}

正在测试的XAML:

<StackLayout Orientation="Vertical">
    <Label Text="Welcome to Xamarin Forms!" VerticalOptions="Center" HorizontalOptions="Center" />
    <Entry AutomationId="SOEntry" Text="StackOverflow" />        
</StackLayout>