Bird
Raised Fist0
JUnittesting~20 mins

doReturn and doThrow in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mockito Mastery: doReturn and doThrow
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of doReturn with Mockito
What will be the output of the following JUnit test using Mockito's doReturn?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class Service {
    String getData() { return "real"; }
}

public class ServiceTest {
    @Test
    void testDoReturn() {
        Service mockService = mock(Service.class);
        doReturn("mocked").when(mockService).getData();
        String result = mockService.getData();
        assertEquals("mocked", result);
        System.out.println(result);
    }
}
AThrows NullPointerException
Breal
Cnull
Dmocked
Attempts:
2 left
💡 Hint
doReturn sets the return value for the mocked method call.
❓ Predict Output
intermediate
2:00remaining
Effect of doThrow in Mockito
What happens when the following JUnit test runs with Mockito's doThrow?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class Service {
    void perform() {}
}

public class ServiceTest {
    @Test
    void testDoThrow() {
        Service mockService = mock(Service.class);
        doThrow(new IllegalStateException("fail")).when(mockService).perform();
        assertThrows(IllegalStateException.class, () -> mockService.perform());
    }
}
ATest passes because perform() throws IllegalStateException
BTest fails because perform() returns normally
CTest fails with NullPointerException
DTest fails with AssertionError due to wrong exception
Attempts:
2 left
💡 Hint
doThrow makes the mocked method throw the specified exception.
❓ assertion
advanced
2:30remaining
Correct assertion for doThrow exception message
Which assertion correctly verifies that a mocked method throws an exception with message "error occurred" using doThrow?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class Service {
    void execute() {}
}

public class ServiceTest {
    @Test
    void testExceptionMessage() {
        Service mockService = mock(Service.class);
        doThrow(new RuntimeException("error occurred")).when(mockService).execute();
        // Which assertion below is correct?
    }
}
AassertTrue(() -> mockService.execute().equals("error occurred"));
BRuntimeException ex = assertThrows(RuntimeException.class, () -> mockService.execute()); assertEquals("error occurred", ex.getMessage());
CassertThrows(RuntimeException.class, () -> mockService.execute(), "error occurred");
DassertThrowsMessage(RuntimeException.class, "error occurred", () -> mockService.execute());
Attempts:
2 left
💡 Hint
Use assertThrows to capture the exception and then check its message.
🔧 Debug
advanced
2:30remaining
Why does doReturn fail with spy on final method?
Given a spy on a class with a final method, why does the following code throw an exception?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;

class FinalClass {
    final String finalMethod() { return "real"; }
}

public class SpyTest {
    @Test
    void testDoReturnOnFinal() {
        FinalClass spy = spy(new FinalClass());
        doReturn("mocked").when(spy).finalMethod();
        String result = spy.finalMethod();
    }
}
AThe spy object is null, causing NullPointerException.
BdoReturn requires the method to be static, finalMethod is not static.
CMockito cannot mock or stub final methods by default, so doReturn fails.
DdoReturn only works with interfaces, not classes.
Attempts:
2 left
💡 Hint
Mockito has limitations with final methods unless configured.
🧠 Conceptual
expert
3:00remaining
Difference between doReturn().when() and when().thenReturn()
Which statement correctly explains the difference between doReturn().when() and when().thenReturn() in Mockito?
A<code>doReturn().when()</code> can stub methods on spies without calling the real method, while <code>when().thenReturn()</code> calls the real method on spies during stubbing.
B<code>when().thenReturn()</code> is used only for void methods, <code>doReturn().when()</code> is for non-void methods.
C<code>doReturn().when()</code> is deprecated and should not be used; <code>when().thenReturn()</code> is the modern replacement.
DBoth behave identically in all cases; the difference is only stylistic.
Attempts:
2 left
💡 Hint
Consider how spies behave when stubbing methods.

Practice

(1/5)
1. What is the main purpose of doReturn in JUnit mocking?
easy
A. To specify a value that a mocked method should return when called
B. To make a mocked method throw an exception
C. To verify how many times a method was called
D. To reset the state of a mock object

Solution

  1. Step 1: Understand doReturn usage

    doReturn is used to tell a mock what value to return when a specific method is called.
  2. Step 2: Differentiate from doThrow

    doThrow makes the method throw an exception, not return a value.
  3. Final Answer:

    To specify a value that a mocked method should return when called -> Option A
  4. Quick Check:

    doReturn sets return value [OK]
Hint: Remember: doReturn returns a value, doThrow throws exception [OK]
Common Mistakes:
  • Confusing doReturn with doThrow
  • Thinking doReturn verifies method calls
  • Assuming doReturn resets mocks
2. Which of the following is the correct syntax to make a mock method throw an exception using doThrow?
easy
A. doThrow().when(mockObject).methodName(new IOException());
B. doThrow(IOException).when(mockObject).methodName();
C. doThrow(new IOException()).when(mockObject).methodName();
D. doThrow(new IOException).methodName().when(mockObject);

Solution

  1. Step 1: Recall correct doThrow syntax

    The correct syntax is doThrow(new ExceptionType()).when(mock).method(); to specify the exception and method.
  2. Step 2: Check each option

    doThrow(new IOException()).when(mockObject).methodName(); matches the correct syntax exactly. Others have misplaced parentheses or wrong order.
  3. Final Answer:

    doThrow(new IOException()).when(mockObject).methodName(); -> Option C
  4. Quick Check:

    Correct doThrow syntax = doThrow(new IOException()).when(mockObject).methodName(); [OK]
Hint: Use new Exception() inside doThrow, then when(mock).method() [OK]
Common Mistakes:
  • Omitting 'new' before exception
  • Placing parentheses incorrectly
  • Calling method before when()
3. Given the following code snippet, what will be the output when mockService.getData() is called?
MyService mockService = mock(MyService.class);
doReturn("Hello").when(mockService).getData();
doThrow(new RuntimeException()).when(mockService).getData();
System.out.println(mockService.getData());
medium
A. Hello
B. RuntimeException is thrown
C. null
D. Compilation error

Solution

  1. Step 1: Analyze the order of stubbing

    First doReturn("Hello") is set, then doThrow(RuntimeException) overrides it for the same method.
  2. Step 2: Determine which stub applies on method call

    The last stub doThrow takes effect, so calling getData() throws RuntimeException.
  3. Final Answer:

    RuntimeException is thrown -> Option B
  4. Quick Check:

    Last stub wins, so exception thrown [OK]
Hint: Last doReturn or doThrow for method overrides previous [OK]
Common Mistakes:
  • Assuming first stub applies
  • Expecting returned string instead of exception
  • Thinking code won't compile
4. Identify the error in the following code snippet using doReturn and doThrow:
doReturn("Success").when(mockService).process();
doThrow(new IllegalArgumentException()).when(mockService).process();
doReturn("Done").when(mockService).process();
String result = mockService.process();
medium
A. The code will throw IllegalArgumentException at runtime
B. Cannot use doReturn and doThrow on the same method
C. doThrow must be called after doReturn to work
D. The last doReturn overrides previous stubs, so no error

Solution

  1. Step 1: Understand stub overriding order

    Stubs are applied in order; the last stub for a method is effective.
  2. Step 2: Check the last stub

    The last stub is doReturn("Done"), so calling process() returns "Done" without exception.
  3. Final Answer:

    The last doReturn overrides previous stubs, so no error -> Option D
  4. Quick Check:

    Last stub wins, no exception thrown [OK]
Hint: Last stub for method call is effective, no conflict error [OK]
Common Mistakes:
  • Thinking doThrow always throws exception regardless of order
  • Believing mixing doReturn and doThrow causes compile error
  • Expecting exception thrown despite last stub
5. You want to test a method that calls externalService.fetch(). You want to simulate two calls: the first returns "Data1", the second throws an IOException. Which is the correct way to stub fetch() using doReturn and doThrow?
hard
A. doReturn("Data1").doThrow(new IOException()).when(externalService).fetch();
B. doReturn("Data1").when(externalService).fetch(); doThrow(new IOException()).when(externalService).fetch();
C. doReturn("Data1").when(externalService).fetch(); doReturn("Data2").when(externalService).fetch();
D. doThrow(new IOException()).doReturn("Data1").when(externalService).fetch();

Solution

  1. Step 1: Understand chaining stubs for multiple calls

    Mockito allows chaining stubs with doReturn(...).doThrow(...).when(mock).method(); to simulate sequential calls.
  2. Step 2: Analyze options

    doReturn("Data1").doThrow(new IOException()).when(externalService).fetch(); correctly chains doReturn then doThrow for first return and second throw. Separate doReturn("Data1").when(externalService).fetch(); doThrow(new IOException()).when(externalService).fetch(); overrides stubs, causing all calls to throw the exception. The other options use repeated returns or incorrect order.
  3. Final Answer:

    doReturn("Data1").doThrow(new IOException()).when(externalService).fetch(); -> Option A
  4. Quick Check:

    Chain doReturn then doThrow for sequential calls [OK]
Hint: Chain doReturn().doThrow() for sequential call behaviors [OK]
Common Mistakes:
  • Overwriting stubs instead of chaining
  • Wrong order of doThrow and doReturn
  • Expecting multiple when() calls for sequence
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