检查HTML元素是否存在

Luk*_*Luk 2 c# watin automated-tests

我正在使用Watin进行UI测试(Watir,适用于java人).我需要检查HTML中是否存在元素.截至今天,我这样做如下:

    [FindBy(Id = "pnConfirmation")]
    protected Div Confirmation;

    public bool ConfirmationMessageDisplayed
    {
        get
        {
            try
            {
                return Confirmation.Text != "";
            }
            catch (ElementNotFoundException)
            {
                return false;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但这需要花费大量的时间.有没有更有效的方法来做到这一点?

pro*_*ick 5

每当你打电话给Confirmation.TextWatiN等待,直到元素存在.在那之后ElementNotFoundException被抛出.默认情况下,WatiN等待30秒才能显示元素.这可以通过设置值来改变Settings.WaitUntilExistsTimeOut.

要解决您的问题,您可以做几件事.例如,您可以更改此行:

return Confirmation.Text != "";
Run Code Online (Sandbox Code Playgroud)

return Confirmation.Exists && Confirmation.Text != "";
Run Code Online (Sandbox Code Playgroud)

但是你必须记住,false即使这个元素在1秒后出现,它也会返回.如果您想使用该解决方案,我认为您不必捕获此异常,如果您确定,一旦它存在,它将不会被删除.

你当然可以改变它的价值Settings.WaitUntilExistsTimeOut.如果您不想更改此值,但又想稍微等一下,可以使用以下代码替换您的getter:

try
{
    Confirmation.WaitUntilExists(1); //Wait only one second
    return Confirmation.Text != "";
}
catch (WatiN.Core.Exceptions.TimeoutException) //Different exception!
{
    return false;
}
Run Code Online (Sandbox Code Playgroud)