Bird
Raised Fist0
JUnittesting~5 mins

when().thenThrow() for exceptions in JUnit - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What does when().thenThrow() do in JUnit testing?

when().thenThrow() is used to tell a mock object to throw an exception when a specific method is called. It helps test how your code handles errors.

Click to reveal answer
beginner
How do you use when().thenThrow() to simulate an exception?

You write when(mock.method()).thenThrow(new ExceptionType()). This means when method() is called on the mock, it throws the specified exception.

Click to reveal answer
beginner
Why is it useful to throw exceptions in mocks during testing?

Throwing exceptions in mocks lets you check if your code correctly handles errors, like catching exceptions or cleaning up resources.

Click to reveal answer
intermediate
Example: How to mock a method readFile() to throw IOException?
when(mock.readFile()).thenThrow(new IOException("File not found"));

This simulates a file read error in your test.

Click to reveal answer
intermediate
What happens if you forget to handle the exception thrown by when().thenThrow() in your test?

Your test will fail with an unexpected exception unless you catch it or declare it with @Test(expected=Exception.class).

Click to reveal answer
What is the purpose of when().thenThrow() in JUnit mocking?
ATo create a real object
BTo make a mock method return a value
CTo verify a method call
DTo make a mock method throw an exception
Which exception type can you throw using thenThrow()?
AAny exception type
BOnly runtime exceptions
COnly checked exceptions
DNo exceptions
What happens if the mocked method does not throw the exception as expected?
ATest passes silently
BTest ignores the mock
CTest fails because behavior is not as mocked
DMock throws a different exception
How do you write a test that expects an exception thrown by a mock method?
AUse <code>@Test(expected=Exception.class)</code>
BIgnore exceptions
CUse <code>assertEquals()</code>
DNo special handling needed
Which mocking framework commonly uses when().thenThrow() syntax?
AJUnit only
BMockito
CSelenium
DJUnit Jupiter
Explain how when().thenThrow() helps test exception handling in your code.
Think about how you test code reacting to errors.
You got /3 concepts.
    Describe the steps to mock a method to throw a specific exception using when().thenThrow().
    Focus on the syntax and purpose.
    You got /3 concepts.

      Practice

      (1/5)
      1. What is the main purpose of using when().thenThrow() in JUnit tests?
      easy
      A. To verify that a method returns a specific value
      B. To skip the execution of a test method
      C. To create a new instance of a class
      D. To simulate an exception being thrown by a mocked method

      Solution

      1. Step 1: Understand the role of when().thenThrow()

        This syntax is used in mocking frameworks like Mockito to simulate exceptions when a mocked method is called.
      2. Step 2: Identify the purpose in testing

        It helps test how your code handles exceptions by forcing the mocked method to throw an exception.
      3. Final Answer:

        To simulate an exception being thrown by a mocked method -> Option D
      4. Quick Check:

        Exception simulation [OK]
      Hint: Use when().thenThrow() to simulate errors in mocks [OK]
      Common Mistakes:
      • Confusing exception simulation with return value mocking
      • Thinking it creates real exceptions instead of simulated ones
      • Using it to skip tests instead of throwing exceptions
      2. Which of the following is the correct syntax to make a mocked method throw an IllegalArgumentException using Mockito?
      easy
      A. when(mock.method()).throwException(IllegalArgumentException)
      B. when(mock.method()).thenThrow(new IllegalArgumentException())
      C. mock.method().thenThrow(IllegalArgumentException)
      D. when(mock.method()).throws(IllegalArgumentException)

      Solution

      1. Step 1: Recall Mockito syntax for throwing exceptions

        The correct syntax uses when(mock.method()).thenThrow(new ExceptionType()).
      2. Step 2: Match the options with correct syntax

        when(mock.method()).thenThrow(new IllegalArgumentException()) matches the correct syntax exactly, creating a new exception instance inside thenThrow().
      3. Final Answer:

        when(mock.method()).thenThrow(new IllegalArgumentException()) -> Option B
      4. Quick Check:

        Correct Mockito exception syntax [OK]
      Hint: Use thenThrow(new Exception()) with when() for exceptions [OK]
      Common Mistakes:
      • Using throwException or throws which are not Mockito methods
      • Not creating a new exception instance
      • Calling thenThrow directly on mock.method()
      3. Given the following code snippet, what will be the test result?
      MyService mockService = mock(MyService.class);
      when(mockService.getData()).thenThrow(new RuntimeException("Error"));
      
      assertThrows(RuntimeException.class, () -> mockService.getData());
      medium
      A. Test passes because RuntimeException is thrown as expected
      B. Test fails because no exception is thrown
      C. Test fails due to syntax error in when().thenThrow()
      D. Test passes but exception type is incorrect

      Solution

      1. Step 1: Analyze the mocking behavior

        The mocked method getData() is set to throw a RuntimeException when called.
      2. Step 2: Understand the assertion

        assertThrows expects a RuntimeException from calling mockService.getData().
      3. Final Answer:

        Test passes because RuntimeException is thrown as expected -> Option A
      4. Quick Check:

        Exception thrown matches assertThrows [OK]
      Hint: assertThrows expects the exception thrown by thenThrow() [OK]
      Common Mistakes:
      • Assuming no exception is thrown from mocked method
      • Confusing exception types in assertThrows
      • Thinking thenThrow causes syntax errors
      4. Identify the error in the following test code using Mockito:
      when(mockService.getData()).thenThrow(RuntimeException.class);
      assertThrows(RuntimeException.class, () -> mockService.getData());
      medium
      A. Missing try-catch block around mockService.getData()
      B. assertThrows should not be used with exceptions
      C. Incorrect use of thenThrow with exception class instead of instance
      D. No error; code is correct

      Solution

      1. Step 1: Check thenThrow argument type

        thenThrow requires an exception instance, not a class type.
      2. Step 2: Identify correct usage

        The code should use thenThrow(new RuntimeException()) instead of passing the class.
      3. Final Answer:

        Incorrect use of thenThrow with exception class instead of instance -> Option C
      4. Quick Check:

        thenThrow needs exception instance [OK]
      Hint: Use new Exception() inside thenThrow(), not exception class [OK]
      Common Mistakes:
      • Passing exception class instead of instance to thenThrow
      • Expecting assertThrows to catch exceptions without mocking
      • Adding unnecessary try-catch in test
      5. You want to test that your service handles a NullPointerException thrown by a dependency's void call() method. Which of the following code snippets correctly mocks the dependency and verifies the exception handling using JUnit and Mockito?
      hard
      A. doThrow(new NullPointerException()).when(dependency).call(); assertThrows(NullPointerException.class, () -> service.callDependency());
      B. when(dependency.call()).thenThrow(NullPointerException.class); assertThrows(Exception.class, () -> service.callDependency());
      C. when(dependency.call()).thenReturn(null); assertThrows(NullPointerException.class, () -> service.callDependency());
      D. when(dependency.call()).thenThrow(new NullPointerException()); assertThrows(NullPointerException.class, () -> service.callDependency());

      Solution

      1. Step 1: Understand mocking exceptions with void methods

        If dependency.call() is a void method, doThrow().when() is the correct way to mock exceptions.
      2. Step 2: Verify correct assertion

        assertThrows(NullPointerException.class, () -> service.callDependency()) correctly checks that the service handles the exception.
      3. Step 3: Analyze options

        when(dependency.call()).thenThrow(new NullPointerException()); assertThrows(NullPointerException.class, () -> service.callDependency()); uses when().thenThrow() which works only for non-void methods. when(dependency.call()).thenThrow(NullPointerException.class); assertThrows(Exception.class, () -> service.callDependency()); passes class instead of instance and wrong exception type in assertion. when(dependency.call()).thenReturn(null); assertThrows(NullPointerException.class, () -> service.callDependency()); returns null instead of throwing exception.
      4. Final Answer:

        doThrow(new NullPointerException()).when(dependency).call(); assertThrows(NullPointerException.class, () -> service.callDependency()); -> Option A
      5. Quick Check:

        Use doThrow for void methods + assertThrows [OK]
      Hint: Use doThrow() for void methods, then assertThrows() to check [OK]
      Common Mistakes:
      • Using thenThrow() on void methods
      • Passing exception class instead of instance
      • Asserting wrong exception type
      • Returning null instead of throwing exception
      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