@Test
annotation provides an optional argument 'expected', by using this, you can
test the exception thrown by a method.
Example
@Test(expected=IllegalArgumentException.class)
public void
divide_10By0_IllegalArgumentException() {
Arithmetic obj1 = new
Arithmetic();
obj1.divide(10, 0);
}
Find
the below working application.
package com.sample.arithmetic; public class Arithmetic { public int divide(int a, int b) { if (b == 0) { throw new IllegalArgumentException("Division by zero is not supported"); } return a / b; } }
ArithmeticTest.java
package com.sample.arithmetic; import org.junit.Test; /** * Test cases follow below naming convention. * methodName_input_output format. * * @author krishna * */ public class ArithmeticTest { @Test(expected=IllegalArgumentException.class) public void divide_10By0_IllegalArgumentException() { Arithmetic obj1 = new Arithmetic(); obj1.divide(10, 0); } }
Above
approach is good in testing the exceptions thrown by a method. Sometimes you
may want to test the exception message also. In my next post, I will explain about
this.
No comments:
Post a Comment