0
0
JUnittesting~5 mins

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

Choose your learning style9 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.