@Test(expected) Method
The expected parameter is used along with @Test annotation.
Using the “expected” parameter can specify the exception name our test may throw.
Program
Let’s start our example by creating a sample class called divideByZero.java, and it contains a simple method that will print in the console that this method is trying to divide by zero, which will throw Arithmetic Exception.
package com.aditya04848.junit.helper;
public class divideByZero{
public void function(){
System.out.println("Trying to divide by zero will throw Arithmetic Exception");
int divide = 1/0;
}
}

You can also try this code with Online Java Compiler
Run Code
Test
We have to create a test file for the above class called divideByZeroTest.java. We are simply creating an obj of the divideByZero class and calling it inside the @Test.
Since inside the @Test annotation, we have provided the expected argument value to be ArithmeticException.class, which means this test is expecting an ArithmeticException.
Now when obj.function() is called, it tries to divide by zero and throws an ArithmeticException, which is why the test is successfully passed.
package com.aditya04848.junit.helper;
import org.junit.Test;
public class divideByZeroTest {
divideByZero obj = new divideByZero();
@Test(expected = ArithmeticException.class)
public void functionTest(){
obj.function();
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Following will be the output in console and JUnit.
Output Console:

Output JUnit:

Testing Exceptions using @Rule
@Test method is useful only when we want to assert that a specific exception is thrown or not.
We can use the ExpectedException rule to verify some other properties of the exception.
In the below example code, apart from asserting the expected exception, we're also asserting that the code that attempts to parse an Integer value will result in a NumberFormatException with the message "For input string."
Example Test
In this example test, we create an exception rule under @Rule annotation, and using exceptionRule.expect(), we are excepting the NumberFormatException exception. Since Integer.parseInt("abc") will throw NumberFormatException, the following test code will pass successfully. We can also check the expectMessage using exceptionRule.
package com.aditya04848.junit.helper;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class NumberFormatExpection {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test
public void testFunction() {
exceptionRule.expect(NumberFormatException.class);
exceptionRule.expectMessage("For input string");
Integer.parseInt("abc");
}
}

You can also try this code with Online Java Compiler
Run Code
Output

FAQs
-
What happens if a method throws an exception In JUnit?
JUnit will fail the test if the method does throw the exception. Note the difference: that test case does not test that the exception is thrown and caught (an implementation detail), it tests that the method does not throw or propagate an exception in the situation that a call to csvReader.read will throw an exception.
-
When to use try/catch In JUnit?
The try/catch has its limits. This approach is helpful for simple cases, like a testing message in the exception or domain object.
-
Does the @before method get its instance in JUnit?
Each test creates an instance of the test class and invokes the test. After all, tests are executed, the "@AfterAll" annotated static methods are called.
-
How do I uninstall JUnit?
Delete the directory structure where you unzipped the JUnit distribution.
Remove junit.jar from the CLASSPATH.
JUnit does not modify the registry, so removing all the files will thoroughly uninstall it.
Key Takeaways
In conclusion, exception handling is significant because we expect a method to throw an exception in some situations. For example, if we have a divide method and 0 is given as a denominator argument, we expect this divide method to throw Arithmetic Exception.
In JUnit, we can assert exceptions using the @Test(exception) method, and we just have to provide the value of exception to be equal to the expected exception this test should throw. We can also assert exceptions using @Rule annotation.
Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!
Happy Reading!