Testng: Skip/Failed Rest of Tests If There is An E

2019-03-06 11:32发布

问题:

I am writing my tests using Selenium and TestNG on Java. How can I skip/fail the rest of a Test when an exception is caught?

For example like if I have 3 steps on a test

@Test(priority = 1)
    public void login() {

    }

    @Test(priority = 2)
    public void checkLoginResult() {

    }

    @Test(priority = 3)
    public void submitImage() {

    }

How can I skip the rest of the test for example if there is a Selenium exception caught (TimeOutException i.e) on the first test 'login'?

Is there some annotation or any method that can be used for this purpose?

Thanks

回答1:

Check dependsOnMethods in the TestNG documentation:

http://testng.org/doc/documentation-main.html#dependencies-with-annotations

If you add this parameter to the second and third test, they won't get executed if the first test failed:

@Test(priority = 1)
public void login() {

}

@Test(priority = 2, dependsOnMethods = {"login"})
public void checkLoginResult() {

}

@Test(priority = 3, dependsOnMethods = {"login"})
public void submitImage() {

}


回答2:

@Test(priority = 2,dependsOnMethods={"login"})
    public void checkLoginResult() {

    }

    @Test(priority = 3,dependsOnMethods={"login","checkLoginResult"})
    public void submitImage() {

    }

This way the dependents will be skipped. To fail them write a listener class where you can check after every method failure, if the method that failed has depndant methods and then you can fail them. Something like this can be done.