How to write test case for exception in Junit
What you will learn here about Junit
- How to write test case for exception in Junit
Sometimes we come to situation where we want to write test case for exception. So here we will see how to write test case for exception in Junit.
How to write test case for exception in junit
Please follow the following steps to know how to write test case for exception in junit
1)First create a maven project
2)Then add the maven dependency for junit which is shown below
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency>
3)Now please create a class whose test case you want to write which is shown below
public class Calculator{ public static void main(String[] args) { Calculator calculator=new Calculator(); try { double rs=calculator.divide(10,2); System.out.println(rs); } catch(Exception exe) { exe.printStackTrace(); } } public double divide(int dividend, int divisor) throws ArithmeticException { return dividend/divisor; } }
4)Now please write the test case which is shown below
import org.junit.Assert; import org.junit.Test; public class CalculatorTest { @Test public void dividetest() { Calculator calculator=new Calculator(); Assert.assertThrows("Not arithmetic thrown",ArithmeticException.class,() -> calculator.divide(1, 0)); } @Test(expected = ArithmeticException.class) public void divideTest() { Calculator calculator=new Calculator(); calculator.divide(1, 0); } }
5)Now please click on Run to run the test case