如何使用 Java 和 Selenium WebDriver 验证登录页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22614290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to valid a login page using Java and Selenium WebDriver?
提问by Ahmed Yaslem
In my database I have the username = [email protected] and password = javachap
在我的数据库中,我有用户名 = [email protected] 和密码 = javachap
If I run the code below, it passes the test although the username and password does not exist in my database.
如果我运行下面的代码,它会通过测试,尽管我的数据库中不存在用户名和密码。
@Test
public void testLogin()
{
String username="abc";
String password="123";
boolean valueFound=false;
// Check the db
try
{
pstmt=conn.prepareCall("select * from user where USR_EMAIL=? and USD_PASSWORD=?");
pstmt.setString(1,username);
pstmt.setString(2,password);
rs=pstmt.executeQuery();
valueFound = rs.next();
}
catch(Exception e)
{
// report some error
}
采纳答案by Lucas
public class LoginPageTest extends IntegrationTest {
private HtmlUnitDriver driver;
@Before
public void setup() throws MalformedURLException, UnknownHostException{
driver = new HtmlUnitDriver(true);
driver.get(System.getProperty("login.url"));
}
@Test
public void testAuthenticationFailureWhenProvidingBadCredentials(){
driver.findElement(By.id("username")).sendKeys("fakeuser");
driver.findElement(By.id("password")).sendKeys("fakepassword");
driver.findElement(By.id("login")).click();
assertTrue(driver.getCurrentUrl().endsWith("failed"));
}
@Test
public void testAuthenticationSuccessWhenProvidingCorrectCredentials(){
driver.findElement(By.id("username")).sendKeys("validuser");
driver.findElement(By.id("password")).sendKeys("validpassword");
driver.findElement(By.id("login")).click();
assertTrue(driver.getCurrentUrl().endsWith("/<name_of_webapp>/"));
}
}
That's how I do it for example.
例如,我就是这样做的。
EDIT: I just noticed comments. Anyway my code shows how you test the actual login page with Selenium.
编辑:我刚刚注意到评论。无论如何,我的代码显示了如何使用 Selenium 测试实际登录页面。
回答by Anand Bharti
public class Ace {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D://jars//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://your login url");
driver.findElement(By.name("username")).sendKeys("enter username");
//pay attention here By.name or By.id, see the page source properly
driver.findElement(By.name("password")).sendKeys("enter password");
driver.findElement(By.xpath("//button[@value='login']")).click();
driver.findElement(By.name("participant")).sendKeys("BLRFC1");
driver.findElement(By.xpath("//button[@type='submit']")).click();
}
}