是否有一种替代方法可以完成Assert所做的工作,并在测试失败时完全执行测试,而无需使用Try Catch

本文关键字:测试 失败 执行 Try Catch 工作 一种 方法 是否 Assert | 更新日期: 2023-09-27 18:09:22

我正在为UI编写测试,并使用断言语句来检查当断言失败时,是否存在一个元素与消息的字符串。我希望测试继续检查其他元素,即使它没有找到一个元素。我还希望有有用的消息,显示当断言在测试结束时失败。

Assert.IsTrue(IsElementPresent(By.XPath("//a/img[@src='/Img1.png']")), "Img1 not present");
Assert.IsTrue(IsElementPresent(By.XPath("//a/img[@src='/Img2.png']")), "Img2 not present");
Assert.IsTrue(IsElementPresent(By.XPath("//a/img[@src='/Img3.png']")), "Img3 not present");

是否有使用assert语句或在try catch中使用assert语句以继续测试的替代方法?

是否有一种替代方法可以完成Assert所做的工作,并在测试失败时完全执行测试,而无需使用Try Catch

您可以保留错误消息,然后在最后进行检查。下面的代码很糟糕,你可能会想要整理一下,但它给了你一个想法,你可以做什么。

[Test]
public void All_images_are_present()
{
    string message = string.Empty;
    message = AssertImage("Img1");
    message += AssertImage("Img2");
    message += AssertImage("Img3");
    ... etc ...
    Assert.That(message, Is.Empty, message);
}
private static string AssertImage(string imageName)
{
    string imagePath = string.Format(@"//a/img[@src='/{0}.png']", imageName);
    if (IsElementPresent(By.XPath("//a/img[@src='/Img1.png']")))
        return string.Empty;
    return string.Format("{0} not present;");    
}

但是,最好有三个不同的测试,并检查每个测试中的每个图像。理想情况下,每个测试应该检查一个功能。

在编程中,我们称之为"if语句"。Assert.IfTrue(condition, message)仅仅是

的简写形式
if (condition) then
    print message
    abort_execution
end-if

解决方案的最佳方法是使用参数化测试。在NUnit中,您可以通过使用[TestCase]属性来实现。

将以下示例重写为参数化测试:

[TestCase("//a/img[@src='/Img1.png']")]
[TestCase("//a/img[@src='/Img2.png']")]
[TestCase("//a/img[@src='/Img3.png']")]
public void ElementIsPresent(string xpath)
{
    Assert.IsTrue(IsElementPresent(By.XPath(xpath)));
}

现在,您可以区分两种类型的红色测试:一种是期望不同的(这里:如果返回false而不是true),另一种是抛出异常的。

你的方法还有一个问题。正如Andy Nichols所提到的,您在一个测试中测试了多个逻辑断言。单元测试在每个测试中应该不超过一个逻辑断言。按照上述参数化测试可以保证您在一个测试中测试一个逻辑断言。