我之前只使用过 Java,但需要在 C# 中设置一些测试。
在登录测试中,我喜欢有一个等待方法来等待设置登录 cookie。
在 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");
}
}
最佳答案
在 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;
}
在 dotnet 绑定(bind)中,ExpectedConditions
消费时不需要WebDriverWait.Until<T>
。您只需发送 Func<IWebDriver, T>
适合你的情况。
还值得注意的是,如果 Until
未能满足条件,它将在抛出之前检查配置的忽略异常类型列表。 -Details on configuring these
有关使用 dotnet 绑定(bind)获取 cookie 的更多详细信息,请查看 ICookieJar界面。
有关使用 dotnet 绑定(bind)进行自定义等待的其他信息通常可以在 here 中找到。 .
希望这有帮助!
关于java - 如何在 C# Selenium WebDriver 中等待登录 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42341417/