Bird
Raised Fist0
JUnittesting~15 mins

Why different doubles serve different purposes in JUnit - Automation Benefits in Action

Choose your learning style10 modes available
Verify behavior of different test doubles in a payment processing system
Preconditions (3)
Step 1: Use DummyPaymentGateway to create a PaymentProcessor instance and call processPayment with any amount
Step 2: Use StubPaymentGateway that returns true for processPayment and verify PaymentProcessor accepts payment
Step 3: Use FakePaymentGateway that simulates real payment logic and verify PaymentProcessor behavior
Step 4: Use SpyPaymentGateway to record if processPayment was called and verify the call count
Step 5: Use MockPaymentGateway to expect processPayment call with specific amount and verify interaction
✅ Expected Result: Each test double behaves according to its purpose: Dummy is a placeholder, Stub returns canned data, Fake has working logic, Spy records calls, Mock verifies interactions
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Assert that PaymentProcessor processes payment correctly with Stub and Fake
Verify Spy records method calls
Verify Mock expects specific method calls with correct parameters
Best Practices:
Use Mockito for creating mocks and spies
Use clear and descriptive test method names
Use assertions from JUnit Jupiter Assertions
Keep tests independent and focused on one double per test
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

import org.junit.jupiter.api.Test;

interface PaymentGateway {
    boolean processPayment(double amount);
}

class PaymentProcessor {
    private final PaymentGateway gateway;

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

    public boolean makePayment(double amount) {
        return gateway.processPayment(amount);
    }
}

// Dummy: does nothing, just placeholder
class DummyPaymentGateway implements PaymentGateway {
    public boolean processPayment(double amount) {
        return false; // not used
    }
}

// Stub: returns fixed value
class StubPaymentGateway implements PaymentGateway {
    public boolean processPayment(double amount) {
        return true; // always success
    }
}

// Fake: simple working implementation
class FakePaymentGateway implements PaymentGateway {
    public boolean processPayment(double amount) {
        return amount > 0; // success if amount positive
    }
}

// Spy and Mock will be created by Mockito

public class PaymentProcessorTest {

    @Test
    void testWithDummy() {
        PaymentGateway dummy = new DummyPaymentGateway();
        PaymentProcessor processor = new PaymentProcessor(dummy);
        // Dummy does nothing, result is false
        assertFalse(processor.makePayment(100));
    }

    @Test
    void testWithStub() {
        PaymentGateway stub = new StubPaymentGateway();
        PaymentProcessor processor = new PaymentProcessor(stub);
        assertTrue(processor.makePayment(100));
    }

    @Test
    void testWithFake() {
        PaymentGateway fake = new FakePaymentGateway();
        PaymentProcessor processor = new PaymentProcessor(fake);
        assertTrue(processor.makePayment(50));
        assertFalse(processor.makePayment(0));
    }

    @Test
    void testWithSpy() {
        PaymentGateway real = new StubPaymentGateway();
        PaymentGateway spy = spy(real);
        PaymentProcessor processor = new PaymentProcessor(spy);

        processor.makePayment(200);
        processor.makePayment(300);

        verify(spy, times(2)).processPayment(anyDouble());
    }

    @Test
    void testWithMock() {
        PaymentGateway mock = mock(PaymentGateway.class);
        when(mock.processPayment(150)).thenReturn(true);

        PaymentProcessor processor = new PaymentProcessor(mock);
        boolean result = processor.makePayment(150);

        assertTrue(result);
        verify(mock).processPayment(150);
    }
}

This test class shows how different test doubles serve different purposes.

Dummy is a placeholder that does nothing; it helps satisfy dependencies but is not used.

Stub returns fixed data to simulate a successful payment.

Fake has simple logic to simulate real behavior.

Spy wraps a real object and records method calls, verified with verify().

Mock is a fully controlled double where we set expectations and verify interactions.

Each test method focuses on one double type, uses clear assertions, and follows best practices for readability and maintainability.

Common Mistakes - 4 Pitfalls
Using Dummy as if it returns meaningful data
Not verifying interactions when using Mocks
Using real implementations instead of Fakes for complex logic
Not isolating tests and mixing multiple doubles in one test
Bonus Challenge

Now add data-driven testing with 3 different payment amounts using Stub and verify results

Show Hint

Practice

(1/5)
1. Which test double is primarily used to provide predefined data to the code under test without verifying interactions?
easy
A. Stub
B. Mock
C. Spy
D. Fake

Solution

  1. Step 1: Understand the role of a stub

    A stub provides fixed data or responses to the code being tested but does not check if methods were called.
  2. Step 2: Differentiate from mocks and spies

    Mocks verify interactions, spies do both spying and stubbing, and fakes are simplified implementations. Only stubs focus on providing data without verification.
  3. Final Answer:

    Stub -> Option A
  4. Quick Check:

    Stub = provides data only [OK]
Hint: Stubs give data, mocks check calls, spies do both [OK]
Common Mistakes:
  • Confusing mocks with stubs
  • Thinking spies only provide data
  • Mixing fakes with stubs
2. Which of the following is the correct way to create a mock object using Mockito in JUnit?
easy
A. MyClass mock = spy(new MyClass());
B. MyClass mock = new MyClass();
C. MyClass mock = Mockito.mock(MyClass.class);
D. MyClass mock = new FakeMyClass();

Solution

  1. Step 1: Recall Mockito syntax for mocks

    Mockito.mock(Class.class) creates a mock object for the given class.
  2. Step 2: Identify incorrect options

    MyClass mock = new MyClass(); creates a real object, not a mock. MyClass mock = spy(new MyClass()); creates a spy, not a mock. MyClass mock = new FakeMyClass(); uses a fake class, not a mock.
  3. Final Answer:

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

    Mockito.mock() creates mocks [OK]
Hint: Use Mockito.mock(Class.class) to create mocks [OK]
Common Mistakes:
  • Using new keyword instead of Mockito.mock
  • Confusing spy() with mock()
  • Assuming fake classes are mocks
3. Given the following code snippet using Mockito:
List<String> list = Mockito.spy(new ArrayList<>());
list.add("one");
Mockito.verify(list).add("one");
System.out.println(list.size());

What will be printed?
medium
A. 0
B. null
C. Throws an exception
D. 1

Solution

  1. Step 1: Understand spy behavior

    A spy wraps a real object and records interactions but calls real methods unless stubbed.
  2. Step 2: Analyze the code execution

    Adding "one" to the spy list calls the real add method, so the list size becomes 1. The verify confirms the add call happened.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    Spy calls real methods and records calls [OK]
Hint: Spy calls real methods and tracks calls [OK]
Common Mistakes:
  • Thinking spy does not call real methods
  • Assuming size remains 0 after add
  • Expecting null or exception output
4. Identify the error in this Mockito test code:
MyService service = Mockito.mock(MyService.class);
service.process();
Mockito.verify(service.process());
medium
A. Missing MockitoAnnotations.initMocks(this) call
B. verify() should receive a method call without parentheses
C. verify() should be called before process()
D. process() method cannot be mocked

Solution

  1. Step 1: Understand Mockito verify syntax

    Mockito.verify() expects the mock object as argument, then the method call without parentheses inside verify.
  2. Step 2: Identify the mistake in code

    The code calls verify(service.process()), which calls process() immediately and passes its result. Correct is verify(service).process().
  3. Final Answer:

    verify() should receive a method call without parentheses -> Option B
  4. Quick Check:

    Use verify(mock).method() syntax [OK]
Hint: Use verify(mock).method() without parentheses inside verify [OK]
Common Mistakes:
  • Calling method inside verify() parentheses
  • Calling verify before method execution
  • Confusing mock initialization with verification
5. You want to test a method that calls an external payment service. You need to check that the payment method was called with correct parameters, but also want to return a fixed success response. Which test double should you use?
hard
A. Mock
B. Spy
C. Stub
D. Fake

Solution

  1. Step 1: Understand requirements for the test double

    You want to verify the method call (like a mock) and also provide a fixed response (like a stub).
  2. Step 2: Identify the double that combines both features

    A mock verifies interactions and can return fixed responses when configured with when(mock.method(params)).thenReturn(success).
  3. Final Answer:

    Mock -> Option A
  4. Quick Check:

    Mock = verify calls + stub data [OK]
Hint: Mock verifies calls and stubs responses [OK]
Common Mistakes:
  • Using stub which can't verify calls
  • Using spy which executes real methods unless stubbed
  • Confusing fake with mock
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