继续下一次测试IF assertEquals失败

时间:2015-08-16 20:59:56

标签: java selenium selenium-webdriver

我在Java / Selenium中相当新,我正在尝试自动化一些测试。 所以我想要做的是移动到下一行代码如果此测试失败并在此测试通过时打印消息。 现在,我强迫此测试失败,以便转移到下一个操作。 这是我的一段代码:

public class SelfReportingTest {
private WebDriver driver;

@Before
 public void SetUp() {
         driver = new FirefoxDriver();
 }

@Test
public void TestLoginFunctionality() 

String validUsername = "testUsername";
String validPassword = "testPassword";
String validUrl = "https://testsite.com/users/profile/show" // URL when user is successfully logged

driver.get("http://testsite.com");
WebElement loginLink =driver.findElement(By.id("loginLink"));
    loginLink.click();

WebElement usernameField = driver.findElement(By.id("LoginUserName"));

WebElement passwordField = driver.findElement(By.id("LoginPassword"));
usernameField.sendKeys(validUsername);
passwordField.sendKeys(validPassword);

WebElement loginButton =driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div[1]/form/div/div[2]/input"));
loginButton.click();

if(validUrl != driver.getCurrentUrl()) {
        driver.get("http://test.jira.com");
    }
    else { 
        System.out.println("login successfull");

我在IF条件下挣扎 - 无论用户名/密码是否正确/不正确,始终采取第一个条件。 比较URL并不是强制性的,我可以用一些WebElements来做,但我不确定这是正确的方法吗? 我尝试了assertEquals但它只是在实际和预期不相等时失败,所以它不符合我的需要。 你们可以提出一些建议,在这种情况下会有效吗? 提前致谢。

2 个答案:

答案 0 :(得分:0)

尝试使用assert.True(driver.getTitle()=="page name");或查找元素并检查IsDisplayed

例如:driver.findElement(By.Id("")).isDisplayed;

答案 1 :(得分:0)

You care checking the current URL with your assigned URL as "validURl" which is : 

String validUrl = "https://testsite.com/users/profile/show"

Some time the Current URL string changed after login so if you do an exact match it may return you FALSE. But you can check .contains() which will compare 2 string and check the existence of validUrl in driver.getCurrentUrl().

Your code ( But Note its not the BEST way, you can use .equals or .contains)

    if(!driver.getCurrentUrl().equals(validUrl)) {
            driver.get("http://test.jira.com");
        }
        else { 
            System.out.println("login successfull");


The better way to check the Page Title as it may move from Login to Home  or you can verify any existence of the web element in the page ( Note add a try catch block during finding webElement to print the else part as if the exception will come in if the else will not get get executed and you will not see the sysout statement you have added.


try(){
 if(driver.fineElement(By.<Element in your home Page after login>)){
  {
   Print You are Logged in
   }
}
catch(exception elementNotfound){
Print You are not logged in as Exception comes on Finding the Element
}


There are better way to handle the code using driverListener but you can now start with this.

So the Page title verification is a good idea for you to check you are in Login Page of Home Page
相关问题