FluentAutomation 與 IWebDriver 混搭使用

      在〈FluentAutomation 與 IWebDriver 混搭使用〉中留言功能已關閉

雖然  FluentAutomation 語意比較完整

public class TestFluentAutomation : FluentTest
{
    public void TestLogin()
    {
        var testUrl = "";

        I.Open(testUrl);
        I.Enter("test").In("#account");
        I.Enter("123456").In("#password");
        I.Click("input[type=\"submit\"]");
    }
}

但有時候要做一些JavaScript 的操作時,卻又想要回頭用 IWebDriver

例如 : Scroll

((IJavaScriptExecutor)Driver).ExecuteScript($"window.scrollBy(0,{100})");

或者取得屬性

var span = Driver.FindElement(By.TagName("span"));
 
var text = span.GetAttribute("aria-label");

安裝 FluentAutomation.SeleniumWebDriver

安裝 Selenium.Chrome.WebDriver

其實做的事情就是繼承 FluentTest , 然後未來使用改使用 CFluentTest 就可以呼叫 Driver 使用 IWebDriver

    /// <summary>
    /// 自訂 FluentTest ,產生 ChromeDriver 與 baseURL
    /// </summary>
    public class CFluentTest : FluentTest
    {
        protected IWebDriver Driver;

        public CFluentTest()
        {
            FluentAutomation.FluentSettings.Current.ScreenshotPath = @"D:\Capture";

            ChromeOptions options = new ChromeOptions();

            //不註解的話,會隱藏背景執行
            //options.AddArgument("--headless");

            Driver = new ChromeDriver(options);

            FluentSettings.Current.ContainerRegistration = (container) =>
            {
                FluentTest.IsMultiBrowserTest = true;

                var webDrivers = new List<Func<IWebDriver>> {() => Driver};

                var commandProviders =
                    new CommandProviderList(
                        webDrivers.Select(x => new CommandProvider(x, new LocalFileStoreProvider())));
                container.Register<CommandProviderList>(commandProviders);

                container.Register<ICommandProvider, MultiCommandProvider>();
                container.Register<IAssertProvider, MultiAssertProvider>();
                container.Register<IFileStoreProvider, LocalFileStoreProvider>();
            };
        }
    }

一個簡單的應用,自動按讚範例

    public class WebPlayer : CFluentTest
    {
        public void Play()
        {
            I.Open(BaseUrl);

            I.Enter("account").In("input[name=\"username\"]");

            I.Enter("password").In("input[name=\"password\"]");

            Driver.FindElement(By.Name("password")).SendKeys(Keys.Enter);

            System.Threading.Thread.Sleep(1000);

            ((IJavaScriptExecutor)Driver).ExecuteScript($"window.scrollBy(0,{100})");

            var elements = Driver.FindElements(By.ClassName("coreSpriteHeartOpen"));

            var span = elements[0].FindElement(By.TagName("span"));

            var text = span.GetAttribute("aria-label");

            if (text == "讚")
            {
                elements[0].Click();
            }

            Driver.Close();
            Driver.Dispose();

        }
    }
print