Tuesday 8 July 2014

Timeout and Expected condition in Selenium Webdriver using JUnit



Sometimes we need to set timeout condition in your test or we need to mention expected consition in selenium webdriver



Timeout Test In JUnit For WebDriver

-> The timeout function used onlt in @Test annotation.
-> Supposing you have written test for one module and you wants to set timeout for your test.
-> Here timeout means allowed maximum time to complete full test.
-> Here Execution allowed for mentioned timeout value. After that mentioned timeout value,it will skip remaining stpes and marked the function as error in console.

Example :

@Test(timeout=1000)
 public void test1(){  
 }

From above example, it will allow 1000 milli sec for execution.

if it will take more than 1000 milli sec for execution means it will skip remaining stes inside the function. And come out from test1() function and test1() marked as error.



Expected Exception Test In JUnit For WebDriver

-> some times we are expecting some exception during your webdriver test execution and that exception which is acceptable.
-> If you are using junit framework for your webdriver test then you can do it very easily.
-> We can specify expected exception condition with @Test annotation as bellow.

@Test(expected = NullPointerException.class)
 public void exceptiontest2() {
 }

Here my expected exception is null pointer exception so my expected condition is NullPointerException.class. You can write your expected exception like IndexOutOfBoundsException.class, ArithmeticException.class, etc.


Example :

@Test(timeout=2000)
 public void test1() throws InterruptedException{
 driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest2 class-test1");
 System.out.print("\njunittest2 class-test1 executed before sleep");
 Thread.sleep(5000);
 System.out.print("\njunittest2 class-test1 executed after sleep");
 }

 @Test
 public void exceptiontest1() {
     throw new NullPointerException();
 }

 @Test(expected = NullPointerException.class)
 public void exceptiontest2() {
  throw new NullPointerException();
 }



Console Output :

Browser open
junittest2 class-test1 executed before sleep
Browser close

-> test1() method is display with error because test was time out after 2000 milisecond as per our condition.
-> exceptiontest2() pass successfully because we have placed expected exception condition with it.
-> exceptiontest1() display with error because there was not any expected exception condition.

No comments:

Post a Comment