Expected Exceptions attribute:
This expectedExceptions
present in @Test in TestNG
While
writing unit tests there can be certain scenarios where we need to verify that
an exception is being thrown by the program during execution.
TestNG
provides a feature to test such scenarios by allowing the user to specify the type of exceptions that are expected to
be thrown by a test method during
execution. It supports multiple values being provided for verification. If the
exception thrown by the test is not part of the user entered list, the test
method will be marked as failed.
we write
ExpectedExceptions as the part of @Test. we need write exception with .class
extension.
We can write
both checked excpetions , unchecked exceptions and our own customized
exceptions.
we can write
single exception,multiple exceptions as well.For example
@Test(expectedExceptions=ArithmeticException.class)
@Test(expectedExceptions
= { IOException.class })
@Test(expectedExceptions
= { IOException.class, NullPointerException.class })
Example:
package
com.rameshsoft.testNG;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import
org.testng.annotations.AfterMethod;
import
org.testng.annotations.BeforeMethod;
import
org.testng.annotations.Test;
public class
ExpectedExecptionDemo {
@BeforeMethod
public void
before()
{
System.out.println("Before
test running");
}
@AfterMethod
public void
after()
{
System.out.println("After
test running");
}
@Test(expectedExceptions=IOException.class)
public void
execute1() throws IOException
{
System.out.println("RameshSoft");
throw new
IOException();
}
@Test(expectedExceptions=ArithmeticException.class)
public
void execute()
{
System.out.println(10/0);
System.out.println("Hello");
}
}
Output:
Before test running
After test running
Before test running
Rameshsoft
After test running
PASSED: execute
PASSED: execute1
No comments:
Post a Comment