Bird
Raised Fist0
JUnittesting~20 mins

Stub objects in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Stub Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple stub method call
What will be the output of this JUnit test using a stub object?
JUnit
public interface Calculator {
    int add(int a, int b);
}

public class CalculatorStub implements Calculator {
    @Override
    public int add(int a, int b) {
        return 42; // stub always returns 42
    }
}

@Test
public void testAdd() {
    Calculator calc = new CalculatorStub();
    int result = calc.add(5, 3);
    System.out.println(result);
}
A42
B8
C0
DCompilation error
Attempts:
2 left
💡 Hint
Remember, a stub returns fixed values regardless of input.
❓ assertion
intermediate
2:00remaining
Correct assertion for stubbed method
Which assertion correctly verifies the stubbed method returns the expected value?
JUnit
public interface Service {
    String getData();
}

public class ServiceStub implements Service {
    @Override
    public String getData() {
        return "stubbed data";
    }
}

@Test
public void testGetData() {
    Service service = new ServiceStub();
    String data = service.getData();
    // Which assertion is correct here?
}
AassertFalse(data.equals("stubbed data"));
BassertEquals("stubbed data", data);
CassertNull(data);
DassertTrue(data == "stubbed data");
Attempts:
2 left
💡 Hint
Use the proper JUnit assertion to compare string values.
🔧 Debug
advanced
2:00remaining
Identify the stub causing test failure
Given this test and stub, why does the test fail?
JUnit
public interface UserRepository {
    boolean exists(String username);
}

public class UserRepositoryStub implements UserRepository {
    @Override
    public boolean exists(String username) {
        return false; // stub always returns false
    }
}

@Test
public void testUserExists() {
    UserRepository repo = new UserRepositoryStub();
    boolean exists = repo.exists("admin");
    assertTrue(exists);
}
AThe test is missing a setup method to initialize the stub.
BThe stub method signature is incorrect causing a compile error.
CThe stub always returns false, so assertTrue fails.
DThe assertTrue method is used incorrectly with a boolean.
Attempts:
2 left
💡 Hint
Check what the stub method returns and what the assertion expects.
🧠 Conceptual
advanced
1:30remaining
Purpose of stub objects in unit testing
What is the main purpose of using stub objects in unit testing?
ATo replace real components with fixed responses to isolate the unit under test.
BTo automatically generate test cases based on code coverage.
CTo measure performance and load of the application.
DTo simulate user input events in UI testing.
Attempts:
2 left
💡 Hint
Think about how stubs help focus tests on one part of the code.
❓ framework
expert
2:30remaining
Using Mockito to create a stub method
Which Mockito code snippet correctly stubs a method to return "hello" when called?
JUnit
public interface GreetingService {
    String greet();
}

@Test
public void testGreet() {
    GreetingService mockService = Mockito.mock(GreetingService.class);
    // Which line stubs greet() to return "hello"?
}
AMockito.mockReturn(mockService.greet(), "hello");
BMockito.stub(mockService.greet()).toReturn("hello");
CMockito.given(mockService.greet()).willReturn("hello");
DMockito.when(mockService.greet()).thenReturn("hello");
Attempts:
2 left
💡 Hint
Check the correct Mockito syntax for stubbing methods.

Practice

(1/5)
1. What is the main purpose of a stub object in JUnit testing?
easy
A. To replace a real object with fixed responses for controlled testing
B. To generate random data during test execution
C. To speed up the compilation of test classes
D. To automatically fix bugs found during testing

Solution

  1. Step 1: Understand the role of stub objects

    Stub objects are used to replace real parts of a system with simple implementations that return fixed data.
  2. Step 2: Identify the purpose in testing

    This allows tests to run in isolation and control the test environment by providing predictable responses.
  3. Final Answer:

    To replace a real object with fixed responses for controlled testing -> Option A
  4. Quick Check:

    Stub objects = fixed responses for isolation [OK]
Hint: Stub = fixed answers to isolate tests quickly [OK]
Common Mistakes:
  • Confusing stubs with mocks or spies
  • Thinking stubs generate random data
  • Believing stubs fix bugs automatically
2. Which of the following is the correct way to create a simple stub in JUnit using an anonymous class?
easy
A. MyService service = new MyService(); service.getValue() = 5;
B. MyService service = new MyService.getValue(5);
C. MyService service = new MyService() { public int getValue() { return 5; } };
D. MyService service = new MyService() -> 5;

Solution

  1. Step 1: Recognize Java anonymous class syntax

    Creating a stub often uses an anonymous class overriding methods to return fixed values.
  2. Step 2: Check each option's syntax

    MyService service = new MyService() { public int getValue() { return 5; } }; correctly overrides getValue() to return 5. Options A, C, and D have invalid Java syntax.
  3. Final Answer:

    MyService service = new MyService() { public int getValue() { return 5; } }; -> Option C
  4. Quick Check:

    Anonymous class override = MyService service = new MyService() { public int getValue() { return 5; } }; [OK]
Hint: Anonymous class overrides method with fixed return [OK]
Common Mistakes:
  • Trying to assign a value directly to a method call
  • Using incorrect method call syntax
  • Confusing lambda syntax with anonymous classes
3. Given the stub below, what will be the output of testService.getValue()?
class TestService {
  int getValue() { return 0; }
}

TestService testService = new TestService() {
  @Override
  int getValue() { return 10; }
};
System.out.println(testService.getValue());
medium
A. Runtime exception
B. 0
C. Compilation error
D. 10

Solution

  1. Step 1: Understand method overriding in anonymous class

    The anonymous class overrides getValue() to return 10 instead of 0.
  2. Step 2: Determine output of the print statement

    Calling testService.getValue() invokes the overridden method, so it returns 10.
  3. Final Answer:

    10 -> Option D
  4. Quick Check:

    Overridden method returns 10 [OK]
Hint: Overridden method in stub returns new value [OK]
Common Mistakes:
  • Assuming original method runs instead of overridden
  • Thinking anonymous class causes compile error
  • Expecting runtime exceptions without errors
4. Identify the error in the following stub creation code snippet:
MyService service = new MyService() {
  public int getValue() {
    return "five";
  }
};
medium
A. Cannot override getValue method
B. Method getValue returns wrong data type
C. Missing semicolon after class definition
D. Anonymous class syntax is incorrect

Solution

  1. Step 1: Check method return type consistency

    The method getValue() is declared to return int, but returns a String "five".
  2. Step 2: Verify syntax correctness

    The anonymous class syntax and semicolon are correct; overriding is allowed.
  3. Final Answer:

    Method getValue returns wrong data type -> Option B
  4. Quick Check:

    Return type mismatch causes error [OK]
Hint: Return type must match method signature [OK]
Common Mistakes:
  • Ignoring return type mismatch
  • Assuming syntax error instead of type error
  • Thinking overriding is disallowed
5. You want to test a component that depends on a slow external service. Which stub implementation approach is best to speed up tests while ensuring predictable results?
hard
A. Create a stub class that returns fixed, pre-defined data instantly
B. Use the real external service but limit the number of calls
C. Mock the external service to record calls without returning data
D. Skip testing the component until the external service is faster

Solution

  1. Step 1: Identify the problem with the real service

    The external service is slow, which slows down tests and makes results unpredictable.
  2. Step 2: Choose a stub approach for speed and predictability

    Creating a stub that returns fixed data instantly allows fast, reliable tests without depending on the real service.
  3. Step 3: Evaluate other options

    Using the real service or skipping tests delays feedback; mocking without return data doesn't help test results.
  4. Final Answer:

    Create a stub class that returns fixed, pre-defined data instantly -> Option A
  5. Quick Check:

    Stub fixed data = fast, predictable tests [OK]
Hint: Stub fixed data for fast, reliable tests [OK]
Common Mistakes:
  • Using real slow service in tests
  • Confusing mocks with stubs
  • Skipping tests instead of isolating dependencies
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