简体   繁体   中英

WebDriver + TestNG - How to handle test results

I'm quite new to WebDriver and TestNG framework. I've started with a project that does a regression test of an e-commerce website. I'm done with the login and registration and so on. But there is something that I don't quite understand.

Example, I have this easy code that searches for a product.

driver.get(url + "/k/k.aspx");
driver.findElement(By.id("q")).clear();
driver.findElement(By.id("q")).sendKeys("xxxx"); //TODO: Make this dynamic
driver.findElement(By.cssSelector("input.submit")).click();

Now I want to check if xxxx is represented on the page. This can be done with

webdriver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*xxxxxx[\\s\\S]*$")

I store this in a Boolean and check if its true or false.

Now to the question, based on this Boolean value I want to say that the test result is success or fail. How can I do that? What triggers a testNG test to fail?

TestNG or any other testing tool decides success or failure of a test based on assertion.

Assert.assertEquals(actualVal, expectedVal);

So if actualVal and expectedVal are same then test will pass else it will fail.

Similarly you will find other assertion options if you using any IDE like Eclipse.

If you want to stop your test execution based on the verification of that text value, then you can use Asserts. However, if you want to log the outcome of the test as a failure and carry on, you should try using soft assertions, which log the verification as passed or failed and continue with the test. Latest Testng comes equipped to handle this - info at Cedric's blog

write this code where your if condition fails

throw new RuntimeException("XXXX not found: ");

u can use throw exception, and each method which will cal this meth should also throw Excetion after method name or you can use try catch. sample:

protected Boolean AssertIsCorrectURL(String exedctedURL) throws Exception {

String errMsg = String.format("Actual URL page: '%s'. Expected URL page: '%s'",
this.driver.getCurrentUrl(), exedctedURL);
throw new Exception(errMsg);
}

You can do this.

boolean result = webdriver.findElement(By.cssSelector("BODY")).getText().matches("^[\s\S] xxxxxx[\s\S] $") Assert.assertTrue(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM