Bird
Raised Fist0
JUnittesting~20 mins

Mock objects in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mock Objects Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple Mockito mock behavior
What is the output of the following JUnit test using Mockito when the mocked method is called without stubbing?
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 Data";
    }
}

public class MockTest {
    @Test
    void testMock() {
        Service mockService = mock(Service.class);
        String result = mockService.getData();
        System.out.println(result);
        assertNull(result);
    }
}
Anull
B"Real Data"
CThrows NullPointerException
DEmpty string ""
Attempts:
2 left
💡 Hint
Think about what Mockito returns by default for unstubbed methods that return objects.
❓ assertion
intermediate
1:30remaining
Correct Mockito verification syntax
Which of the following Mockito verification statements correctly verifies that the method process() was called exactly twice on a mock object named mockProcessor?
Averify(mockProcessor, times(1)).process();
Bverify(mockProcessor).process(2);
Cverify(mockProcessor, atLeast(2)).process();
Dverify(mockProcessor, times(2)).process();
Attempts:
2 left
💡 Hint
Check the Mockito syntax for verifying exact number of invocations.
🔧 Debug
advanced
2:30remaining
Identify the cause of NullPointerException in Mockito test
Given the following test code, why does it throw a NullPointerException?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class Repository {
    String fetch() {
        return "data";
    }
}

class Service {
    private Repository repo;
    Service(Repository repo) { this.repo = repo; }
    String getData() {
        return repo.fetch().toUpperCase();
    }
}

public class NullPointerTest {
    @Test
    void testService() {
        Repository mockRepo = mock(Repository.class);
        Service service = new Service(mockRepo);
        String result = service.getData();
        assertEquals("DATA", result);
    }
}
AThe Service constructor is not called properly, so repo is null.
BMockito mock creation failed due to missing annotation.
CThe mockRepo.fetch() returns null by default, so calling toUpperCase() causes NullPointerException.
DassertEquals is used incorrectly causing the exception.
Attempts:
2 left
💡 Hint
What does Mockito return for unstubbed methods that return objects?
🧠 Conceptual
advanced
1:30remaining
Purpose of using mock objects in unit testing
What is the main reason to use mock objects in unit testing?
ATo isolate the unit under test by simulating dependencies and controlling their behavior.
BTo improve the performance of the application in production.
CTo replace the need for writing actual test cases.
DTo automatically generate test data for integration tests.
Attempts:
2 left
💡 Hint
Think about why we want to control external parts when testing a single unit.
❓ framework
expert
3:00remaining
Behavior of Mockito spy vs mock
Consider the following code snippet using Mockito. What will be the output when calling spyList.get(0)?
JUnit
import static org.mockito.Mockito.*;
import java.util.*;
import org.junit.jupiter.api.Test;

public class SpyTest {
    @Test
    void testSpy() {
        List<String> list = new ArrayList<>();
        list.add("one");
        List<String> spyList = spy(list);
        when(spyList.get(0)).thenReturn("two");
        System.out.println(spyList.get(0));
    }
}
A"one"
B"two"
CIndexOutOfBoundsException
DNullPointerException
Attempts:
2 left
💡 Hint
Remember that spy calls real methods unless stubbed.

Practice

(1/5)
1. What is the main purpose of using mock objects in JUnit testing?
easy
A. To speed up the compilation of test classes
B. To simulate real objects and control their behavior during tests
C. To replace the JUnit framework with a simpler tool
D. To automatically generate test data without coding

Solution

  1. Step 1: Understand the role of mock objects

    Mock objects imitate real objects to isolate the code being tested and control responses.
  2. Step 2: Identify the main benefit in testing

    This helps test code without relying on actual implementations or external systems.
  3. Final Answer:

    To simulate real objects and control their behavior during tests -> Option B
  4. Quick Check:

    Mock objects = simulate and control behavior [OK]
Hint: Mocks simulate objects to isolate tests quickly [OK]
Common Mistakes:
  • Thinking mocks speed up compilation
  • Confusing mocks with test data generators
  • Believing mocks replace the JUnit framework
2. Which of the following is the correct way to create a mock object using Mockito in JUnit?
easy
A. MyClass mock = mock(MyClass.class);
B. MyClass mock = new MyClass().mock();
C. Mock<MyClass> mock = new Mock<>();
D. MyClass mock = createMock(MyClass);

Solution

  1. Step 1: Recall Mockito syntax for creating mocks

    Mockito uses mock(Class.class) to create mock objects.
  2. Step 2: Match the syntax to options

    MyClass mock = mock(MyClass.class); matches the correct syntax: MyClass mock = mock(MyClass.class);
  3. Final Answer:

    MyClass mock = mock(MyClass.class); -> Option A
  4. Quick Check:

    Mockito mock creation = mock(Class.class) [OK]
Hint: Use mock(Class.class) to create mocks in Mockito [OK]
Common Mistakes:
  • Using new Mock<>() which is not valid
  • Calling mock() on an instance
  • Using createMock which is not Mockito syntax
3. Given the following code snippet, what will result be after execution?
List<String> mockList = mock(List.class);
when(mockList.size()).thenReturn(5);
int result = mockList.size();
medium
A. 5
B. 0
C. Throws NullPointerException
D. Returns the actual size of a real list

Solution

  1. Step 1: Understand the mock setup

    The mock list's size() method is stubbed to return 5 when called.
  2. Step 2: Evaluate the method call

    Calling mockList.size() returns 5 as per the stub, not the real list size.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Stubbed method returns set value 5 [OK]
Hint: Stubbed methods return specified values, not defaults [OK]
Common Mistakes:
  • Expecting default 0 for int return
  • Thinking mock calls throw exceptions by default
  • Confusing mock with real object behavior
4. Identify the error in the following JUnit test code using Mockito:
MyService service = mock(MyService.class);
when(service.getData()).thenReturn("data");
verify(service).getData();
medium
A. No error, code is correct
B. Incorrect use of mock() method
C. Cannot verify void methods
D. Missing call to service.getData() before verify

Solution

  1. Step 1: Understand verify usage in Mockito

    Verification checks if a method was called on the mock during the test.
  2. Step 2: Check if method was called before verify

    The code never calls service.getData() before verify, so verification fails.
  3. Final Answer:

    Missing call to service.getData() before verify -> Option D
  4. Quick Check:

    Verify requires method call before checking [OK]
Hint: Always call method before verify to avoid errors [OK]
Common Mistakes:
  • Verifying without calling the method
  • Confusing mock creation syntax
  • Thinking verify only works on void methods
5. You want to test a method that calls a dependency twice with different inputs and expects different outputs. How do you configure a mock to return "first" on the first call and "second" on the second call to getValue()?
hard
A. when(mock.getValue()).thenReturn("first"); when(mock.getValue()).thenReturn("second");
B. when(mock.getValue()).thenReturn(new String[]{"first", "second"});
C. when(mock.getValue()).thenReturn("first").thenReturn("second");
D. when(mock.getValue()).thenReturn("second").thenReturn("first");

Solution

  1. Step 1: Recall Mockito chaining for multiple returns

    Mockito allows chaining thenReturn() calls to specify sequential return values.
  2. Step 2: Match chaining syntax to options

    when(mock.getValue()).thenReturn("first").thenReturn("second"); matches the correct chaining syntax for sequential calls.
  3. Final Answer:

    when(mock.getValue()).thenReturn("first").thenReturn("second"); -> Option C
  4. Quick Check:

    Chain thenReturn() for multiple call returns [OK]
Hint: Chain thenReturn() calls for sequential mock returns [OK]
Common Mistakes:
  • Passing multiple values in one thenReturn() call
  • Overwriting stubs instead of chaining
  • Reversing the order of return values
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