Bird
Raised Fist0
JUnittesting~20 mins

Why exception testing validates error handling in JUnit - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Exception Testing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this JUnit test when the method throws the expected exception?
Consider this JUnit 5 test method that expects an IllegalArgumentException. What will be the test result when the tested method throws this exception?
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;

class ExampleTest {
    @Test
    void testException() {
        assertThrows(IllegalArgumentException.class, () -> {
            throw new IllegalArgumentException("Invalid argument");
        });
    }
}
ATest passes because the expected exception was thrown.
BTest fails because the exception message does not match exactly.
CTest fails because no exception was thrown.
DTest passes but logs a warning about the exception.
Attempts:
2 left
💡 Hint
Remember that assertThrows expects the specified exception type to be thrown for the test to pass.
❓ assertion
intermediate
2:00remaining
Which assertion correctly verifies that a method throws NullPointerException?
You want to write a JUnit 5 test that confirms a method throws NullPointerException when called with null. Which assertion is correct?
AassertTrue(method(null) instanceof NullPointerException);
BassertEquals(NullPointerException.class, method(null));
CassertThrows(NullPointerException.class, () -> method(null));
DassertDoesNotThrow(() -> method(null));
Attempts:
2 left
💡 Hint
Use the assertion designed to check for exceptions.
🧠 Conceptual
advanced
2:00remaining
Why is exception testing important for validating error handling?
Which statement best explains why exception testing is crucial in software testing?
AIt ensures the program crashes immediately on errors.
BIt replaces the need for functional testing of normal behavior.
CIt prevents any exceptions from ever occurring during execution.
DIt verifies that the program handles error conditions gracefully by throwing expected exceptions.
Attempts:
2 left
💡 Hint
Think about how programs should behave when something goes wrong.
🔧 Debug
advanced
2:00remaining
Identify the problem in this exception test code
This JUnit 5 test is supposed to check that a method throws IndexOutOfBoundsException, but it always passes even if no exception is thrown. What is wrong?
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;

class DebugTest {
    @Test
    void testException() {
        try {
            methodThatShouldThrow();
        } catch (IndexOutOfBoundsException e) {
            // expected
        }
    }

    void methodThatShouldThrow() {
        // no exception thrown here
    }
}
AThe test does not use assertThrows, so it passes even if no exception is thrown.
BThe catch block swallows the exception, causing the test to fail.
CThe method throws a different exception type, causing a test error.
DThe test method is missing the @Test annotation.
Attempts:
2 left
💡 Hint
Consider how JUnit knows a test should fail when an exception is missing.
❓ framework
expert
2:00remaining
How does JUnit 5's assertThrows improve exception testing compared to older methods?
Which feature of assertThrows in JUnit 5 makes exception testing more reliable and readable than older try-catch based tests?
AIt catches all exceptions silently, so tests never fail due to exceptions.
BIt automatically fails the test if the expected exception is not thrown, reducing boilerplate code.
CIt requires manual verification of exception messages after catching exceptions.
DIt disables exception handling during test execution to speed up tests.
Attempts:
2 left
💡 Hint
Think about how assertThrows simplifies test code and failure detection.

Practice

(1/5)
1. Why is exception testing important in JUnit for validating error handling?
easy
A. It ensures the code correctly throws expected exceptions when errors occur.
B. It improves the speed of test execution by skipping error cases.
C. It automatically fixes bugs related to exceptions.
D. It prevents exceptions from being thrown during normal execution.

Solution

  1. Step 1: Understand the purpose of exception testing

    Exception testing checks if the program throws the right error when something goes wrong.
  2. Step 2: Connect exception testing to error handling validation

    By expecting specific exceptions, tests confirm the code handles errors as designed.
  3. Final Answer:

    It ensures the code correctly throws expected exceptions when errors occur. -> Option A
  4. Quick Check:

    Exception testing = Validates error handling [OK]
Hint: Exception tests confirm errors happen as expected [OK]
Common Mistakes:
  • Thinking exception tests fix bugs automatically
  • Believing exception tests speed up all tests
  • Assuming exception tests stop exceptions from occurring
2. Which JUnit 5 syntax correctly tests that a method throws a NullPointerException?
easy
A. @Test void test() { assertThrows(NullPointerException, method()); }
B. @Test void test() { assertThrows(NullPointerException.class, () -> method()); }
C. @Test void test() { assertThrows(() -> method(), NullPointerException.class); }
D. @Test void test() { assertThrows(method(), NullPointerException.class); }

Solution

  1. Step 1: Recall correct assertThrows syntax in JUnit 5

    The method is: assertThrows(ExceptionClass.class, Executable lambda).
  2. Step 2: Match syntax to options

    @Test void test() { assertThrows(NullPointerException.class, () -> method()); } uses assertThrows with exception class first, then lambda, which is correct.
  3. Final Answer:

    @Test void test() { assertThrows(NullPointerException.class, () -> method()); } -> Option B
  4. Quick Check:

    assertThrows(Exception.class, () -> code) [OK]
Hint: Exception class first, then lambda in assertThrows [OK]
Common Mistakes:
  • Swapping argument order in assertThrows
  • Passing method call instead of lambda
  • Omitting .class for exception type
3. Given this JUnit 5 test code:
@Test
void testDivide() {
  assertThrows(ArithmeticException.class, () -> divide(10, 0));
}

int divide(int a, int b) {
  return a / b;
}

What will be the test result?
medium
A. Test fails due to syntax error in assertThrows usage.
B. Test fails because divide method returns 0 instead of throwing exception.
C. Test passes because dividing by zero throws ArithmeticException.
D. Test passes but throws NullPointerException instead.

Solution

  1. Step 1: Analyze divide method behavior

    Dividing by zero in Java throws ArithmeticException automatically.
  2. Step 2: Check assertThrows expectation

    The test expects ArithmeticException when dividing 10 by 0, matching actual behavior.
  3. Final Answer:

    Test passes because dividing by zero throws ArithmeticException. -> Option C
  4. Quick Check:

    Divide by zero throws ArithmeticException [OK]
Hint: Divide by zero throws ArithmeticException [OK]
Common Mistakes:
  • Assuming divide returns 0 on zero divisor
  • Confusing exception types
  • Thinking assertThrows syntax is wrong here
4. Identify the error in this JUnit 5 test that tries to check for IllegalArgumentException:
@Test
void test() {
  assertThrows(IllegalArgumentException.class, method());
}

void method() {
  throw new IllegalArgumentException();
}
medium
A. assertThrows requires a string message as the first argument.
B. IllegalArgumentException is not a checked exception, so assertThrows is invalid.
C. The test method must declare throws IllegalArgumentException.
D. The method call should be inside a lambda, not called directly.

Solution

  1. Step 1: Understand assertThrows parameter requirements

    assertThrows expects a lambda or Executable, not a direct method call.
  2. Step 2: Identify the mistake in test code

    Calling method() directly runs it immediately, causing exception before assertThrows can catch it.
  3. Final Answer:

    The method call should be inside a lambda, not called directly. -> Option D
  4. Quick Check:

    Use lambda () -> method() in assertThrows [OK]
Hint: Wrap method call in lambda for assertThrows [OK]
Common Mistakes:
  • Calling method directly inside assertThrows
  • Thinking checked exceptions are required
  • Adding unnecessary message argument
5. You want to test a method that throws IOException only when a file is missing. Which approach best validates this error handling using JUnit 5 exception testing?
hard
A. Use assertThrows(IOException.class, () -> method("missing.txt")) and verify exception message contains "not found".
B. Use assertThrows(Exception.class, () -> method("missing.txt")) without checking message.
C. Call method("missing.txt") directly and catch IOException in test method.
D. Use try-catch inside method to suppress IOException and assert no exception thrown.

Solution

  1. Step 1: Choose specific exception type for assertThrows

    Testing for IOException ensures only that error triggers the test.
  2. Step 2: Verify exception message for correctness

    Checking the message confirms the exception is due to missing file, not other IO errors.
  3. Final Answer:

    Use assertThrows(IOException.class, () -> method("missing.txt")) and verify exception message contains "not found". -> Option A
  4. Quick Check:

    Specific exception + message check = best validation [OK]
Hint: Test specific exception and check message for accuracy [OK]
Common Mistakes:
  • Using generic Exception instead of IOException
  • Not verifying exception message
  • Suppressing exceptions inside method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard