Bird
Raised Fist0
JUnittesting~20 mins

when().thenReturn() stubbing in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mockito Stubbing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of when().thenReturn() stubbed method call
Given the following JUnit test code using Mockito, what will be the output of the test assertion?
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

interface Calculator {
    int add(int a, int b);
}

public class CalculatorTest {
    @Test
    void testAdd() {
        Calculator calc = mock(Calculator.class);
        when(calc.add(2, 3)).thenReturn(10);
        int result = calc.add(2, 3);
        assertEquals(10, result);
    }
}
ATest fails because the stub returns 5 for add(2, 3)
BTest passes because the stub returns 10 for add(2, 3)
CTest fails with NullPointerException because add is not implemented
DTest fails because the stub returns 0 for add(2, 3)
Attempts:
2 left
💡 Hint
Remember that when().thenReturn() sets the return value for the mocked method call.
❓ assertion
intermediate
2:00remaining
Correct assertion for stubbed method return
You stub a method call with when().thenReturn() to return "Hello". Which assertion correctly verifies this behavior?
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

interface Greeter {
    String greet();
}

public class GreeterTest {
    @Test
    void testGreet() {
        Greeter greeter = mock(Greeter.class);
        when(greeter.greet()).thenReturn("Hello");
        String message = greeter.greet();
        // Which assertion is correct here?
    }
}
AassertEquals("Hello", message);
BassertTrue(message == "Hello");
CassertNull(message);
DassertFalse(message.equals("Hello"));
Attempts:
2 left
💡 Hint
Use assertEquals to compare string values in tests.
🔧 Debug
advanced
2:00remaining
Identify the error in stubbing with when().thenReturn()
What is wrong with the following stubbing code snippet?
JUnit
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.List;

List<String> list = mock(List.class);
when(list.get(0)).thenReturn("first");
when(list.get(anyInt())).thenReturn("any");
String result = list.get(0);
AThe code returns null because mocks do not support stubbing
BThe code throws a NullPointerException because of anyInt() usage
CThe second when() overrides the first, so list.get(0) returns "any" instead of "first"
DThe code causes a compile error because thenReturn() is missing a semicolon
Attempts:
2 left
💡 Hint
Consider the order and specificity of stubbing calls.
🧠 Conceptual
advanced
2:00remaining
Behavior of unstubbed method calls on mocks
If you create a mock object and stub only one method with when().thenReturn(), what happens when you call another method on the mock that was not stubbed?
AThe unstubbed method returns the default value for its return type (e.g., null, 0, false)
BThe unstubbed method throws an exception immediately
CThe unstubbed method returns the last stubbed value
DThe unstubbed method causes the test to fail automatically
Attempts:
2 left
💡 Hint
Think about how Mockito handles unstubbed method calls by default.
❓ framework
expert
3:00remaining
Correct usage of when().thenReturn() with chained method calls
Given a mock object with a method that returns another mock, how do you correctly stub a chained method call using when().thenReturn()?
JUnit
interface Service {
    Repository getRepository();
}
interface Repository {
    String findName();
}

Service service = mock(Service.class);
Repository repo = mock(Repository.class);
// How to stub service.getRepository().findName() to return "Data"?
Awhen(service.getRepository().findName()).thenReturn("Data");
B
when(service.getRepository()).thenReturn(null);
when(repo.findName()).thenReturn("Data");
C
when(service.getRepository().findName()).thenReturn(null);
when(repo.findName()).thenReturn("Data");
D
when(service.getRepository()).thenReturn(repo);
when(repo.findName()).thenReturn("Data");
Attempts:
2 left
💡 Hint
You must stub each method in the chain separately if the intermediate method returns a mock.

Practice

(1/5)
1. What is the main purpose of when().thenReturn() in JUnit testing?
easy
A. To specify a fake return value for a mocked method call
B. To execute the real method instead of a mock
C. To verify that a method was called
D. To create a new instance of the class under test

Solution

  1. Step 1: Understand mocking in tests

    Mocking replaces real objects with fake ones to control behavior during tests.
  2. Step 2: Role of when().thenReturn()

    This syntax sets a fake return value for a method call on a mock object.
  3. Final Answer:

    To specify a fake return value for a mocked method call -> Option A
  4. Quick Check:

    when().thenReturn() = fake return value [OK]
Hint: Remember: when().thenReturn() fakes method results [OK]
Common Mistakes:
  • Thinking it calls the real method
  • Using it on real objects instead of mocks
  • Confusing it with verification methods
2. Which of the following is the correct syntax to stub a method getName() of a mock object userMock to return "Alice"?
easy
A. thenReturn("Alice").when(userMock.getName());
B. when(userMock.getName()).thenReturn("Alice");
C. userMock.when(getName()).thenReturn("Alice");
D. when(userMock.getName() == "Alice");

Solution

  1. Step 1: Recall correct when().thenReturn() syntax

    The correct order is when(methodCall).thenReturn(value);
  2. Step 2: Check each option

    when(userMock.getName()).thenReturn("Alice"); matches the correct syntax exactly; others are invalid or reversed.
  3. Final Answer:

    when(userMock.getName()).thenReturn("Alice"); -> Option B
  4. Quick Check:

    Correct syntax = when().thenReturn() [OK]
Hint: Syntax is when(methodCall).thenReturn(value) [OK]
Common Mistakes:
  • Reversing when() and thenReturn() order
  • Calling when() on the mock object instead of method
  • Using equality inside when()
3. Given the code below, what will result print?
List<String> mockList = mock(List.class);
when(mockList.size()).thenReturn(5);
int result = mockList.size();
System.out.println(result);
medium
A. 0
B. null
C. 5
D. Throws NullPointerException

Solution

  1. Step 1: Understand stubbing of mockList.size()

    The size() method is stubbed to return 5 whenever called on mockList.
  2. Step 2: Check the printed result

    Calling mockList.size() returns 5 as stubbed, so result is 5 and prints 5.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    Stubbed method returns set value [OK]
Hint: Stubbed methods return thenReturn() value, not default [OK]
Common Mistakes:
  • Assuming default mock return 0 instead of stubbed 5
  • Expecting real method execution
  • Confusing null with int return
4. Identify the error in the following stubbing code:
MyService service = new MyService();
when(service.getData()).thenReturn("Mocked Data");
medium
A. Cannot stub a method on a real object, must mock it first
B. Missing semicolon after thenReturn()
C. Incorrect method name getData()
D. thenReturn() cannot return a String

Solution

  1. Step 1: Check object type used in when()

    The object service is a real instance, not a mock, so stubbing is invalid.
  2. Step 2: Understand mocking requirement

    Stubbing works only on mock objects created by mock() or similar methods.
  3. Final Answer:

    Cannot stub a method on a real object, must mock it first -> Option A
  4. Quick Check:

    Stub only mocks, not real objects [OK]
Hint: Stub only mock objects, not real instances [OK]
Common Mistakes:
  • Trying to stub real objects
  • Ignoring need to mock before stubbing
  • Assuming thenReturn() syntax error
5. You want to stub a method calculate(int x) of a mock calculatorMock to return x * 2 for any integer input. Which is the correct way to do this using when().thenReturn()?
hard
A. when(calculatorMock.calculate(2)).thenReturn(4);
B. when(calculatorMock.calculate(anyInt())).thenReturn(x * 2);
C. when(calculatorMock.calculate(anyInt())).thenReturn(2);
D. when(calculatorMock.calculate(anyInt())).thenAnswer(invocation -> (int) invocation.getArgument(0) * 2);

Solution

  1. Step 1: Understand when().thenReturn() limitation

    thenReturn() returns a fixed value, cannot compute based on input parameter.
  2. Step 2: Use thenAnswer() for dynamic return

    thenAnswer() allows lambda to compute return based on method arguments.
  3. Final Answer:

    when(calculatorMock.calculate(anyInt())).thenAnswer(invocation -> (int) invocation.getArgument(0) * 2); -> Option D
  4. Quick Check:

    Dynamic return needs thenAnswer(), not thenReturn() [OK]
Hint: Use thenAnswer() for dynamic returns, not thenReturn() [OK]
Common Mistakes:
  • Trying to compute dynamic values with thenReturn()
  • Using undefined variable x in thenReturn()
  • Stubbing only one input value instead of anyInt()
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