[英]How to wait for login cookie in C# Selenium WebDriver?
Im only been working with Java before but need to set up some tests in C#. 我只是以前使用过Java,但需要在C#中设置一些测试。
In a login test I like to have a wait method waiting for the login cookie to be set. 在登录测试中,我希望有一个等待方法来等待设置登录cookie。
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#? 在Java中,我可以执行类似的操作,但是无法在C#中创建相同的代码,谁能帮助我将此代码转换为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");
}
}
In C# I believe the above would look something like this: 在C#中,我相信上面看起来像这样:
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>
. 在dotnet绑定中,使用
WebDriverWait.Until<T>
时不需要ExpectedConditions
。 You can just send in a Func<IWebDriver, T>
for your condition. 您可以根据需要输入
Func<IWebDriver, T>
。
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. 还值得注意的是,如果
Until
条件不满足条件,它将在抛出之前检查已配置的忽略异常类型的列表。 - Details on configuring these - 有关配置这些的详细信息
For more details on getting cookies with the dotnet bindings check out the ICookieJar interface. 有关使用dotnet绑定获取cookie的更多详细信息,请查看ICookieJar界面。
Additional info on custom waiting with the dotnet bindings in general can be found here . 可以在此处找到有关通常使用dotnet绑定进行自定义等待的其他信息。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.