Expected Exceptions

T 
/**
 * EXPECTED EXCEPTIONS IN JUNIT 4
 * ------------------------------
 * JUnit allows you to verify that a specific exceptin is thrown.
 * 
 * Using:
 *      @Test(expected = SomeException.class)
 * 
 * The test PASSES if the exception is thrown.
 * The test FAILS if:
 *  - no exception is thrown
 *  - a different exception is thrown
 * 
 * This makes it easy to test error conditions or preconditions.
 */

package com.minte9.junit.exceptions;

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;

public class ExpectedExceptionTest {

    @Test(expected = ArithmeticException.class)
    public void no_squares_expected() {
        Squares squares = new Squares();
        squares.average();  // division by zero (exception thrown) - test passes
    }

    @Test public void average() {
        Squares squares = new Squares();
        squares.add(3); // 9
        squares.add(5); // 25
        assertEquals(squares.average(), 17);
    }
}

class Squares {
    private List<Integer> squares = new ArrayList<>();

    public void add(int x) {
        squares.add(x * x); 
    }

    public int average() throws ArithmeticException {
        int total = squares.stream().mapToInt(Integer::intValue).sum();
        return total / squares.size();
    }
}

Main Args Exception

T 
/**
 * TESTING EXCEPTINOS IN main() - NO ARGUMENTS
 * -------------------------------------------
 * Applications often expect command-line arguments.
 * If none are provided, methods like args[0] may throw exceptions.
 * 
 * JUnit can verify both:
 *  - incorrect usage (exception thrown)
 *  - correct usage (normal output)
 */

package com.minte9.junit.exceptions;

import org.junit.Test;

public class MainExceptionTest {

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void no_args_expected() {  // Expected to pass
        App.main(new String[] {});
    }

    @Test 
    public void args() {  // Expected to pass
        App.main(new String[] {"run"}); 
    }
}

class App {
    public static void main(String[] args) {
        String action = args[0];
        System.out.println(action);
    }
}






Questions and answers:
Clink on Option to Answer




1. What must happen for a test using an "expected exception" to PASS?

  • a) The specified exception is thrown
  • b) No exception is thrown

2. When does an expected-exception test FAIL?

  • a) When no exception or a different exception is thrown
  • b) When the test contains multiple assertions

3. What is the purpose of testing a program with missing command-line arguments?

  • a) To verify that the correct exception is thrown for invalid usage
  • b) To check performance of the program

4. Why is exception testing valuable in unit tests?

  • a) It ensures error conditions and preconditions are handled correctly
  • b) It prevents exceptions from ever occurring in code


References: