首页 > 解决方案 > Selenium c#:在不使用 autoID / Class、Instance 等的情况下获取 RemoteWebElement 的新实例的最佳方法是什么?

问题描述

如何在 c# / selenium 中刷新我的 RemoteWebElements?

我有两种方法...

    public static bool ClickMe_Method_1(WindowsDriver<RemoteWebElement> driver, RemoteWebElement button_ToClick)
    {
        //Click
        button_ToClick.Click();

        //Assert the click worked and the button is now not Enabled
        Assert.IsFalse(button_ToClick.Enabled);//This Assert will never work because button_ToClick variable is now out of date and needs to be refreshed in this code somehow.
        return button_ToClick.Enabled;
    }

    public static bool ClickMe_Method_2(WindowsDriver<RemoteWebElement> driver, RemoteWebElement button_ToClick, string automationID)
    {
        //Click
        button_ToClick.Click();

        //This line refreshes the button_ToClick
        //BUT is there a way to do this without passing the automationID? 
        //This is a simple example and will only work where I want to click        
        //the first or only instance of a button with this automation ID so 
        //this solution is not very scalable.
        button_ToClick = driver.FindElementByAccessibilityID(automationID);

        //Assert the click worked and the button is now not Enabled
        Assert.IsFalse(button_ToClick.Enabled);
        return button_ToClick.Enabled;
    }

在上面的代码中,method1总是会失败,因为“button_ToClick”在我的测试解决方案中被点击后没有更新。因此,如果单击有效并且 button_ToClick Enabled 变为 false,我的代码将不知道 Enable 现在变为 = false。

我的问题是:我是否必须传入自动化 ID 并使用 FindElement 方法来查找最新的(如方法 2 中)或者有没有办法让 selenium 更新我拥有的 button_ToClick。

注意:RemoteWeElement(在我的例子中是 button_ToClick)没有自动 ID。除非我遗漏了某些东西,否则没有办法在这个阶段在我的方法中获取它,而无需单独传递自动 ID。

背景:我问这个问题的真正原因是因为有时单独的 autoID 是不够的。我可能正在测试每行都有一个按钮的行表。假设调用方法做了一些聪明的工作,我知道我想点击第四个按钮(索引 = 3,因为计数从零开始)。在这种情况下,我需要第三种方法(在我上面的 2 种方法之后),它必须知道我的自动 ID 和实例。这很痛苦,不那么整洁,我现在将向测试人员介绍这个解决方案,我想要最简单、最易读的代码。

标签: c#selenium

解决方案


推荐阅读