0
0
JUnittesting~5 mins

doReturn and doThrow in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does doReturn() do in JUnit mocking?

doReturn() tells a mock object to return a specific value when a method is called. It is useful when you want to avoid calling the real method.

Click to reveal answer
beginner
How does doThrow() work in JUnit mocking?

doThrow() makes a mock method throw an exception when called. This helps test how your code handles errors.

Click to reveal answer
intermediate
Why use doReturn() instead of when().thenReturn() in JUnit?

doReturn() is safer when mocking methods that are final, private, or have side effects. It avoids calling the real method during setup.

Click to reveal answer
beginner
Show a simple example of doThrow() usage in JUnit.
doThrow(new RuntimeException()).when(mockedObject).someMethod();

This makes someMethod() throw a RuntimeException when called.

Click to reveal answer
intermediate
What is the difference between doReturn() and thenReturn() in JUnit mocking?

thenReturn() is used with when() and calls the real method during setup, which can cause issues. doReturn() does not call the real method and is safer for certain cases.

Click to reveal answer
What does doReturn(value).when(mock).method() do?
ACalls the real method <code>method()</code> on <code>mock</code>.
BThrows an exception when <code>method()</code> is called.
CReturns <code>value</code> when <code>method()</code> is called on <code>mock</code>.
DDoes nothing.
Which method is used to make a mock throw an exception when a method is called?
AdoThrow()
BthenReturn()
CdoReturn()
Dwhen()
Why might you prefer doReturn() over when().thenReturn()?
ABecause <code>doReturn()</code> avoids calling the real method during setup.
BBecause <code>doReturn()</code> is slower.
CBecause <code>when().thenReturn()</code> throws exceptions always.
DBecause <code>doReturn()</code> calls the real method.
What happens if you use doThrow(new Exception()).when(mock).method()?
AThe method returns normally.
BThe method throws the specified exception when called.
CThe method is never called.
DThe mock is reset.
Which of these is NOT a reason to use doReturn()?
AMocking private methods.
BAvoiding side effects during setup.
CMocking final methods.
DCalling the real method during setup.
Explain how doReturn() and doThrow() help in mocking with JUnit.
Think about how you control what a mock does when a method is called.
You got /3 concepts.
    Describe a situation where doReturn() is better than when().thenReturn().
    Consider methods that are hard or risky to call during test setup.
    You got /3 concepts.