Expected Exception Test
Add the optional
Check the below example
Unexpected Exception Test
Declare the exception in the
Add the optional
expected
attribute to the @Test
annotation. The test will pass when the expected exception thrown.Check the below example
import org.junit.Test; public class ExceptionTestDemo { String str; @Test(expected = NullPointerException.class) public void testNullPointerException() { str.toLowerCase(); } }The result will be "pass" because the method thrown expected exception (NullPointerException)
Unexpected Exception Test
Declare the exception in the
throws
clause of the test method and don't catch the exception within the test method. Uncaught exceptions will cause the test to fail with an error.
import org.junit.Test; public class ExceptionTestDemo { String str; @Test public void testNullPointerException() throws NullPointerException { str.toLowerCase(); } }Above example test that fails when the NullPointerExceptoin is thrown
No comments:
Post a Comment