Bird
Raised Fist0
JUnittesting~5 mins

Why advanced mocking handles complex dependencies in JUnit

Choose your learning style10 modes available
Introduction

Advanced mocking helps test parts of a program that depend on many other parts. It makes testing easier by pretending those parts work in a simple way.

When a method calls other methods from different classes that are hard to set up.
When testing a class that depends on external services like databases or web APIs.
When you want to isolate the code under test from complex or slow dependencies.
When you need to simulate different responses from dependencies to test all cases.
When dependencies have side effects that you want to avoid during testing.
Syntax
JUnit
import static org.mockito.Mockito.*;

// Create a mock object
MyDependency mockDep = mock(MyDependency.class);

// Define behavior for mock
when(mockDep.someMethod()).thenReturn(someValue);

// Use mock in test
MyClass obj = new MyClass(mockDep);
obj.methodUnderTest();

// Verify interactions
verify(mockDep).someMethod();

Use mock() to create fake objects that replace real dependencies.

when(...).thenReturn(...) sets what the mock should do when called.

Examples
This creates a mock of MyService and makes getData() return "mocked data".
JUnit
MyService mockService = mock(MyService.class);
when(mockService.getData()).thenReturn("mocked data");
This checks that process() was called exactly twice on the mock.
JUnit
verify(mockService, times(2)).process();
This makes the mock throw an exception when failMethod() is called, to test error handling.
JUnit
doThrow(new RuntimeException()).when(mockService).failMethod();
Sample Program

This test uses advanced mocking to replace the PaymentGateway dependency. It tests that processPayment returns true when the mock gateway charges successfully, and returns false without calling the gateway when the amount is zero.

JUnit
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class PaymentProcessor {
    private PaymentGateway gateway;
    public PaymentProcessor(PaymentGateway gateway) {
        this.gateway = gateway;
    }
    public boolean processPayment(double amount) {
        if (amount <= 0) return false;
        return gateway.charge(amount);
    }
}

interface PaymentGateway {
    boolean charge(double amount);
}

public class PaymentProcessorTest {
    @Test
    void testProcessPaymentSuccess() {
        PaymentGateway mockGateway = mock(PaymentGateway.class);
        when(mockGateway.charge(100.0)).thenReturn(true);

        PaymentProcessor processor = new PaymentProcessor(mockGateway);
        boolean result = processor.processPayment(100.0);

        assertTrue(result);
        verify(mockGateway).charge(100.0);
    }

    @Test
    void testProcessPaymentFailForZeroAmount() {
        PaymentGateway mockGateway = mock(PaymentGateway.class);
        PaymentProcessor processor = new PaymentProcessor(mockGateway);

        boolean result = processor.processPayment(0);

        assertFalse(result);
        verify(mockGateway, never()).charge(anyDouble());
    }
}
OutputSuccess
Important Notes

Advanced mocking helps isolate the code you want to test from complex parts.

Always verify that mocks are called as expected to catch mistakes.

Use mocking to simulate errors and edge cases that are hard to reproduce.

Summary

Advanced mocking makes testing easier by faking complex dependencies.

It helps test code in isolation and control dependency behavior.

Mockito is a popular tool for advanced mocking in JUnit tests.

Practice

(1/5)
1. Why do we use advanced mocking in JUnit tests when dealing with complex dependencies?
easy
A. To automatically generate user interfaces
B. To isolate the code under test and control the behavior of its dependencies
C. To avoid writing any test cases
D. To make the code run faster in production

Solution

  1. Step 1: Understand the purpose of mocking

    Mocking replaces real dependencies with fake ones to isolate the code being tested.
  2. Step 2: Recognize the benefit of advanced mocking

    Advanced mocking allows control over complex dependencies, making tests reliable and focused.
  3. Final Answer:

    To isolate the code under test and control the behavior of its dependencies -> Option B
  4. Quick Check:

    Mocking isolates dependencies [OK]
Hint: Mocking isolates dependencies to test code alone [OK]
Common Mistakes:
  • Thinking mocking speeds up production code
  • Believing mocking removes the need for tests
  • Confusing mocking with UI generation
2. Which of the following is the correct syntax to create a mock object using Mockito in a JUnit test?
easy
A. MyClass mock = Mockito.mock(MyClass.class);
B. MyClass mock = new MyClass();
C. MyClass mock = mockito.create(MyClass);
D. MyClass mock = Mockito.createMock(MyClass);

Solution

  1. Step 1: Recall Mockito mock creation syntax

    Mockito uses the static method mock(Class) to create mock objects.
  2. Step 2: Verify the correct syntax

    The correct syntax is: MyClass mock = Mockito.mock(MyClass.class);
  3. Final Answer:

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

    Mockito.mock(Class) creates mocks [OK]
Hint: Use Mockito.mock(Class.class) to create mocks [OK]
Common Mistakes:
  • Using new keyword instead of Mockito.mock
  • Calling non-existent Mockito methods
  • Incorrect class reference syntax
3. Given the following JUnit test code using Mockito:
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Mock
Repository repo;

@InjectMocks
Service service;

@Test
void testGetData() {
when(repo.fetch()).thenReturn("data");
String result = service.getData();
assertEquals("data", result);
}
}

What will be the test result if repo.fetch() is called inside service.getData()?
medium
A. Test fails because repo.fetch() returns null
B. Test fails due to syntax error in mocking
C. Test throws NullPointerException due to uninitialized repo
D. Test passes because repo.fetch() returns mocked "data"

Solution

  1. Step 1: Understand Mockito annotations usage

    @Mock creates a mock for Repository, and @InjectMocks injects it into Service.
  2. Step 2: Analyze the when-thenReturn setup

    Calling repo.fetch() returns "data" as stubbed, so service.getData() returns "data".
  3. Final Answer:

    Test passes because repo.fetch() returns mocked "data" -> Option D
  4. Quick Check:

    Mock returns stubbed value [OK]
Hint: Stub methods with when().thenReturn() to control outputs [OK]
Common Mistakes:
  • Assuming mocks return null by default
  • Forgetting to initialize mocks with @ExtendWith or MockitoAnnotations
  • Confusing mock injection with real object creation
4. Consider this JUnit test snippet using Mockito:
@ExtendWith(MockitoExtension.class)
class TestClass {
@Mock
Database db;

@Test
void testQuery() {
when(db.query("SELECT * FROM users")).thenReturn(null);
String result = db.query("SELECT * FROM users");
assertNotNull(result);
}
}

What is the problem with this test?
medium
A. The assertion will fail because the mock returns null
B. The syntax of when() is incorrect
C. The mock object db is not created properly
D. The test will pass because null is acceptable

Solution

  1. Step 1: Analyze the stubbed return value

    The mock is set to return null for the query method call.
  2. Step 2: Check the assertion logic

    The test asserts that the result is not null, but the stub returns null, so assertion fails.
  3. Final Answer:

    The assertion will fail because the mock returns null -> Option A
  4. Quick Check:

    Assertion contradicts stubbed null [OK]
Hint: Match stubbed return values with assertions [OK]
Common Mistakes:
  • Ignoring that stub returns null
  • Assuming syntax error without checking code
  • Believing test passes with failing assertions
5. You have a service class that depends on two complex external APIs. You want to write a JUnit test that verifies your service logic without calling these APIs. Which advanced mocking approach best handles this scenario?
hard
A. Manually create fake API responses inside the service code
B. Write integration tests that call the real APIs directly
C. Use Mockito to create mocks for both API clients and inject them into the service
D. Skip testing the service since APIs are complex

Solution

  1. Step 1: Identify the need to isolate service from external APIs

    Testing should avoid calling real APIs to keep tests fast and reliable.
  2. Step 2: Choose advanced mocking to simulate API behavior

    Mockito mocks for API clients allow controlling responses and injecting them into the service.
  3. Final Answer:

    Use Mockito to create mocks for both API clients and inject them into the service -> Option C
  4. Quick Check:

    Mock external APIs to isolate service [OK]
Hint: Mock external dependencies to isolate service logic [OK]
Common Mistakes:
  • Testing with real APIs causing slow or flaky tests
  • Hardcoding fake responses inside service code
  • Avoiding tests due to 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