In this we will see how to write Junit if our method has some logic where we are throwing an exception, something like below.
public void checkEmployeeId(Employee employee) {
if (employee.getEmpId() == null) {
throw new IdNotFoundException(“Id is empty”);
}
}
package test; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; class IdNotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; String message; public IdNotFoundException(String message) { super(); this.message = message; } } class Employee { String empId; String empName; public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public void checkEmployeeId(Employee employee) { if (employee.getEmpId() == null) { throw new IdNotFoundException("Id is empty"); } } } public class TestCaseForException { public static Employee employeeObj; @Rule public ExpectedException thrown = ExpectedException.none(); @BeforeClass public static void beforeClass() { employeeObj = new Employee(); } @Test(expected = IdNotFoundException.class) public void testGetEmployeeDetails() { // empId will be null even we will not set employeeObj.setEmpId(null); employeeObj.checkEmployeeId(employeeObj); thrown.expect(IdNotFoundException.class); } }
Run the above example as a Junit Test.