0
0
JUnittesting~10 mins

Testing multiple exceptions in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a method throws the correct exceptions under different error conditions. It verifies that the method throws IllegalArgumentException when input is an empty string, and NullPointerException when input is null.

Test Code - JUnit 5
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

public class ExceptionTest {

    public void processInput(String input) {
        if (input == null) {
            throw new NullPointerException("Input cannot be null");
        }
        if (input.isEmpty()) {
            throw new IllegalArgumentException("Input cannot be empty");
        }
    }

    @Test
    public void testProcessInput_throwsIllegalArgumentException() {
        ExceptionTest et = new ExceptionTest();
        assertThrows(IllegalArgumentException.class, () -> et.processInput("") );
    }

    @Test
    public void testProcessInput_throwsNullPointerException() {
        ExceptionTest et = new ExceptionTest();
        assertThrows(NullPointerException.class, () -> et.processInput(null) );
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test starts for testProcessInput_throwsIllegalArgumentExceptionJUnit test runner initialized-PASS
2Calls processInput with empty string ""Method executes and checks input-PASS
3Throws IllegalArgumentException with message "Input cannot be empty"Exception thrown as expectedassertThrows verifies IllegalArgumentException is thrownPASS
4Test ends for testProcessInput_throwsIllegalArgumentExceptionTest passed-PASS
5Test starts for testProcessInput_throwsNullPointerExceptionJUnit test runner ready for next test-PASS
6Calls processInput with nullMethod executes and checks input-PASS
7Throws NullPointerException with message "Input cannot be null"Exception thrown as expectedassertThrows verifies NullPointerException is thrownPASS
8Test ends for testProcessInput_throwsNullPointerExceptionTest passed-PASS
Failure Scenario
Failing Condition: Method does not throw the expected exception for given input
Execution Trace Quiz - 3 Questions
Test your understanding
What exception is expected when processInput is called with an empty string?
ANullPointerException
BIndexOutOfBoundsException
CIllegalArgumentException
DNo exception
Key Result
Always write separate test cases for each expected exception to clearly verify different error conditions.