3

Im only been working with Java before but need to set up some tests in C#.

In a login test I like to have a wait method waiting for the login cookie to be set.

In Java I can do something like this, but not able to create the same in C#, can anyone help me convert this code to C#?

    public void getTokenCookie(){
    try {
        wait.until(
                new ExpectedCondition<Cookie>() {
                    @Override
                    public Cookie apply(WebDriver webDriver) {
                        Cookie tokenCookie = driver.manage().getCookieNamed("nameOfCookie");
                        if (tokenCookie != null) {
                            System.out.println("\nToken Cookie added: " + tokenCookie);
                            return tokenCookie;
                        } else {
                            System.out.println("waiting for cookie..");
                            return null;
                        }
                    }
                }
        );

    } catch (Exception e){
        System.out.println(e.getMessage());
        fail("Failed to login, no cookie set");
    }
}
Mr Null
  • 65
  • 2
  • 5

1 Answers1

5

In C# I believe the above would look something like this:

public Cookie GetTokenCookie()
{
    var webDriver = new ChromeDriver(); //or any IWebDriver

    var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));

    Cookie cookie = default(Cookie);

    try
    {
        cookie = wait.Until(driver =>
        {
            Cookie tokenCookie = driver.Manage().Cookies.GetCookieNamed("nameOfCookie");
            if (tokenCookie != null)
            {
                Console.WriteLine("\nToken Cookie added: " + tokenCookie);
                return tokenCookie;
            }
            else
            {
                Console.WriteLine("waiting for cookie...");
                return null;
            }
        });
    }
    catch (Exception e)
    {
        Console.WriteLine($"{e.Message}");
    }

    return cookie;
}

In the dotnet bindings, ExpectedConditions isn't required when consuming WebDriverWait.Until<T>. You can just send in a Func<IWebDriver, T> for your condition.

It's also worth noting that if Until fails to meet the condition it will check the list of configured ignored exception types before throwing. - Details on configuring these

For more details on getting cookies with the dotnet bindings check out the ICookieJar interface.

Additional info on custom waiting with the dotnet bindings in general can be found here.

Hope this helps!

Jordan
  • 639
  • 1
  • 13
  • 30