Bird
Raised Fist0
JUnittesting~20 mins

Why advanced mocking handles complex dependencies in JUnit - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Advanced Mocking Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use advanced mocking in unit tests?

Which statement best explains why advanced mocking is important when testing classes with complex dependencies?

AIt replaces the need for writing assertions by verifying all method calls automatically.
BIt automatically generates test data for all dependencies without any manual setup.
CIt allows the test to run slower but with more detailed logs for debugging.
DIt isolates the class under test by simulating complex dependencies, ensuring tests focus only on the class behavior.
Attempts:
2 left
💡 Hint

Think about why isolating the class from its dependencies helps in testing.

❓ Predict Output
intermediate
2:00remaining
Output of a test using Mockito with complex dependency

What will be the output of this JUnit test using Mockito when the service method is called?

JUnit
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
    @Mock
    private Dependency dependency;

    @InjectMocks
    private Service service;

    @Test
    public void testServiceMethod() {
        when(dependency.getData()).thenReturn("mocked data");
        String result = service.process();
        System.out.println(result);
    }
}

class Service {
    private Dependency dependency;
    public String process() {
        return "Processed: " + dependency.getData();
    }
}

interface Dependency {
    String getData();
}
AProcessed: mocked data
BProcessed: null
CNullPointerException at runtime
DCompilation error due to missing annotations
Attempts:
2 left
💡 Hint

Consider what the mock returns when getData() is called.

❓ assertion
advanced
2:00remaining
Correct assertion for verifying interaction with mock

Which assertion correctly verifies that the mocked dependency's method was called exactly once during the test?

JUnit
verify(dependency, ???).getData();
Aonce()
Bcalled()
Ctimes(1)
DatLeastOnce()
Attempts:
2 left
💡 Hint

Check Mockito's syntax for verifying exact call counts.

🔧 Debug
advanced
2:00remaining
Identify the cause of NullPointerException in a mocked test

Given this test code, why does it throw a NullPointerException?

JUnit
public class ServiceTest {
    private Dependency dependency = new DependencyImpl();
    private Service service = new Service(dependency);

    @Test
    public void testProcess() {
        when(dependency.getData()).thenReturn("mocked data");
        String result = service.process();
        assertEquals("Processed: mocked data", result);
    }
}

class Service {
    private Dependency dependency;
    public Service(Dependency dependency) {
        this.dependency = dependency;
    }
    public String process() {
        return "Processed: " + dependency.getData();
    }
}

interface Dependency {
    String getData();
}

class DependencyImpl implements Dependency {
    public String getData() { return "real data"; }
}
AThe when() method is called on a real object, causing an exception.
BThe service instance is null because dependency is not mocked.
CMockito cannot mock a real instance without @Mock annotation and initialization.
DThe test method is missing the @RunWith(MockitoJUnitRunner.class) annotation.
Attempts:
2 left
💡 Hint

Consider what happens when you call when() on a real object instead of a mock.

❓ framework
expert
3:00remaining
Advanced mocking with multiple dependencies and verification order

In a test with two mocked dependencies, which code snippet correctly verifies that dependencyA.methodA() was called before dependencyB.methodB()?

JUnit
DependencyA dependencyA = mock(DependencyA.class);
DependencyB dependencyB = mock(DependencyB.class);

// code under test calls dependencyA.methodA() then dependencyB.methodB()
A
verify(dependencyA).methodA();
verify(dependencyB).methodB();
B
InOrder inOrder = inOrder(dependencyA, dependencyB);
inOrder.verify(dependencyA).methodA();
inOrder.verify(dependencyB).methodB();
C
verifyOrder(dependencyA, dependencyB);
verify(dependencyA).methodA();
verify(dependencyB).methodB();
D
InOrder order = new InOrder(dependencyA, dependencyB);
order.verify(dependencyB).methodB();
order.verify(dependencyA).methodA();
Attempts:
2 left
💡 Hint

Look for Mockito's way to verify call order between mocks.

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