我对Selenium不是很有经验。我想通过以下方法来测试我的知识,验证表单中的名称字段没有特殊字符。我无法这样做。首先,我尝试将字符放在数组中,并从数组中读取,但我一直在获取Alert失败消息。然后我想到了以下方法,并始终获得输出“有效”。Selenium Webdriver Java验证名字段
import junit.framework.Assert;你会得到无效消息:
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class NameField {
public static FirefoxDriver fx= new FirefoxDriver();
public static String doCheck()
{
fx.get("http://www.gogamers.com/#!blank/gs4id");
String regex = "^[A-Z0-9+$";
String str=fx.findElement(By.id("comp-iikjotq8nameField")).getText();
fx.findElement(By.id("comp-iikjotq8nameField")).sendKeys("@john");
if (str.matches("[" + regex + "]+")){
System.out.println("Invalid character in Name field");
}
else{
System.out.println("valid");
}
return str;
我心目中,如果你给使用sendkey(约翰#,@约翰EG)的名称是。我在想另一件事,我应该使用断言?请建议小样本代码有帮助的最佳方式。
我今天试过的新代码仍然给我有效,当我期待无效。有人可以好好看看吗?我试过两次比赛,并找到
公共类YahooMail {
public static void main(String[] args) {
FirefoxDriver fx= new FirefoxDriver();
fx.get("https://login.yahoo.com/account/create?");
String title=fx.getTitle();
Assert.assertTrue(title.contains("Yahoo"));
//First I send a text, then I get the text
fx.findElement(By.id("usernamereg-firstName")).sendKeys("$John");
fx.findElement(By.id("usernamereg-firstName")).getText();
//This is the String I want to find
String firstName="John";
//If there are these symbols associated with the name-show invalid
String patternString = ".*$%^#:.*";
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(firstName);
if(matcher.find()){
System.out.println("Invalid Name");
}
else{
System.out.println("Valid Name");
}
}
}
它通常是更好地解释了一个解决方案,而不是仅仅张贴的匿名代码的某些行。你可以阅读[我如何写一个好的答案](https://stackoverflow.com/help/how-to-answer),还有[完全解释基于代码的答案](https://meta.stackexchange.com /问题/ 114762 /解释-entirely-%E2%80%8C%E2%80%8Bcode为主,答案) –