Bird
Raised Fist0
JUnittesting~20 mins

Choosing the right test double in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Test Double Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding Test Doubles: Which to Use?

You want to isolate a class under test by replacing its dependency with a test double that records interactions but does not implement any real logic. Which test double should you use?

AStub
BFake
CSpy
DMock
Attempts:
2 left
💡 Hint

Think about which test double lets you verify method calls after the test runs.

❓ Predict Output
intermediate
2:00remaining
Output of JUnit Test Using a Stub

What is the output of the following JUnit test when run?

JUnit
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;

public class PaymentProcessorTest {
    interface PaymentGateway {
        boolean charge(double amount);
    }

    static class PaymentGatewayStub implements PaymentGateway {
        public boolean charge(double amount) {
            return true; // always succeeds
        }
    }

    static class PaymentProcessor {
        private PaymentGateway gateway;

        public PaymentProcessor(PaymentGateway gateway) {
            this.gateway = gateway;
        }

        public boolean process(double amount) {
            return gateway.charge(amount);
        }
    }

    @Test
    void testProcessPayment() {
        PaymentGateway stub = new PaymentGatewayStub();
        PaymentProcessor processor = new PaymentProcessor(stub);
        boolean result = processor.process(100.0);
        assertTrue(result);
    }
}
ATest does not compile
BTest fails due to NullPointerException
CTest fails due to assertion error
DTest passes successfully
Attempts:
2 left
💡 Hint

The stub always returns true for charge, so process should succeed.

❓ assertion
advanced
2:00remaining
Correct Assertion for Mock Verification

Given a mock object mockService in JUnit with Mockito, which assertion correctly verifies that process() was called exactly once?

JUnit
mockService.process();
Averify(mockService, times(1)).process();
BassertEquals(1, mockService.process());
Cverify(mockService).process(1);
DassertTrue(mockService.process.calledOnce());
Attempts:
2 left
💡 Hint

Mockito uses verify() with times() to check call counts.

🔧 Debug
advanced
2:00remaining
Debugging a Test Failure with a Fake

A test using a fake database implementation fails because data is not saved as expected. Which is the most likely cause?

AThe mock was not verified
BThe fake does not implement the save method correctly
CThe stub returns incorrect data
DThe spy did not record interactions
Attempts:
2 left
💡 Hint

Fakes have working implementations; if data is not saved, the implementation may be wrong.

❓ framework
expert
3:00remaining
Choosing the Right Test Double in Complex JUnit Tests

You have a service that depends on a slow external API. You want to test your service's logic without calling the real API, but also want to verify that your service calls the API with correct parameters. Which test double combination is best?

AUse a stub to simulate API responses and a spy to verify method calls
BUse a fake with a working API implementation only
CUse a mock to simulate API and verify calls, no stub needed
DUse a spy only to simulate and verify API calls
Attempts:
2 left
💡 Hint

Consider separating behavior simulation and interaction verification.

Practice

(1/5)
1. Which test double should you use in JUnit when you want to replace a real object and verify that certain methods were called during the test?
easy
A. Mock
B. Stub
C. Fake
D. Spy

Solution

  1. Step 1: Understand the purpose of mocks

    Mocks are used to fake behavior and verify interactions, such as method calls.
  2. Step 2: Compare with other test doubles

    Stubs provide fixed responses, fakes have working implementations, spies record calls but mocks are designed for verification.
  3. Final Answer:

    Mock -> Option A
  4. Quick Check:

    Verify calls = Mock [OK]
Hint: Mocks verify calls; stubs just return data [OK]
Common Mistakes:
  • Confusing stubs with mocks
  • Using fake when verification is needed
  • Thinking spies are the same as mocks
2. Which of the following is the correct way to create a stub in JUnit using Mockito?
easy
A. spy(new Service());
B. when(service.getData()).thenReturn("data");
C. mock(Service.class);
D. verify(service).getData();

Solution

  1. Step 1: Identify stub creation syntax

    Stubs return fixed data; in Mockito, use when(...).thenReturn(...) to stub a method.
  2. Step 2: Check other options

    Verify checks calls, mock creates mocks, spy wraps real objects; only when().thenReturn() stubs.
  3. Final Answer:

    when(service.getData()).thenReturn("data"); -> Option B
  4. Quick Check:

    Stub method = when().thenReturn() [OK]
Hint: Stubs use when().thenReturn() syntax [OK]
Common Mistakes:
  • Using verify() to stub methods
  • Confusing mock() with stub setup
  • Using spy() instead of stub
3. Given the following JUnit test code snippet using Mockito, what will be the output of the assertion?
List<String> list = mock(List.class);
when(list.size()).thenReturn(5);
assertEquals(5, list.size());
medium
A. Test passes because size() returns 5
B. Test fails because size() returns 0 by default
C. Test throws NullPointerException
D. Test fails due to syntax error

Solution

  1. Step 1: Analyze mock behavior

    The list is mocked, and size() is stubbed to return 5.
  2. Step 2: Check assertion

    assertEquals(5, list.size()) compares 5 with stubbed return 5, so it passes.
  3. Final Answer:

    Test passes because size() returns 5 -> Option A
  4. Quick Check:

    Stubbed method returns set value [OK]
Hint: Stubbed methods return set values, so assertion passes [OK]
Common Mistakes:
  • Assuming default mock returns 0
  • Expecting real method call on mock
  • Confusing mock with spy behavior
4. Identify the error in this JUnit test using Mockito:
@Test
void testServiceCall() {
  Service service = mock(Service.class);
  service.process();
  verify(service.process());
}
medium
A. Mock creation syntax is wrong
B. Missing stub for process() method
C. process() method cannot be mocked
D. Incorrect use of verify; should be verify(service).process();

Solution

  1. Step 1: Check verify syntax

    verify() expects the mock object, then method call separately: verify(service).process();
  2. Step 2: Identify error in code

    Current code calls verify(service.process()), which is incorrect syntax and causes compile error.
  3. Final Answer:

    Incorrect use of verify; should be verify(service).process(); -> Option D
  4. Quick Check:

    verify syntax = verify(mock).method() [OK]
Hint: verify() needs mock object, then method call separately [OK]
Common Mistakes:
  • Calling verify with method call inside
  • Forgetting to mock the object
  • Confusing stub and verify usage
5. You want to test a payment processing system. The payment gateway is an external service that charges real money. Which test double should you use in your JUnit tests to avoid real charges but still verify that the payment method was called correctly?
hard
A. Use a stub to return a fixed success response
B. Use a fake with a simple in-memory implementation
C. Use a mock to verify the payment method call
D. Use a spy to wrap the real payment gateway

Solution

  1. Step 1: Understand test goal

    We want to avoid real charges but verify the payment method was called.
  2. Step 2: Choose test double type

    Mocks fake behavior and verify calls, perfect for checking method calls without real effects.
  3. Step 3: Compare other options

    Stubs return fixed data but don't verify calls; fakes have real logic; spies call real methods, risking real charges.
  4. Final Answer:

    Use a mock to verify the payment method call -> Option C
  5. Quick Check:

    Verify calls without real effect = Mock [OK]
Hint: Mocks verify calls without real side effects [OK]
Common Mistakes:
  • Using spy risks real external calls
  • Using stub misses call verification
  • Choosing fake adds unnecessary complexity
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