Bird
Raised Fist0
JUnittesting~20 mins

Fake objects in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Fake Object Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a JUnit test using a fake object
Consider the following JUnit test using a fake object to simulate a database. What will be the test result when running this code?
JUnit
public class UserServiceTest {
    static class FakeDatabase implements Database {
        public boolean saveUser(String user) {
            return true; // Always succeeds
        }
    }

    @org.junit.Test
    public void testSaveUser() {
        Database db = new FakeDatabase();
        UserService service = new UserService(db);
        boolean result = service.registerUser("Alice");
        org.junit.Assert.assertTrue(result);
    }
}

interface Database {
    boolean saveUser(String user);
}

class UserService {
    private final Database db;
    public UserService(Database db) {
        this.db = db;
    }
    public boolean registerUser(String user) {
        return db.saveUser(user);
    }
}
ATest fails because the fake database returns false
BTest passes because the fake database always returns true
CTest fails with NullPointerException due to uninitialized database
DTest fails with AssertionError because assertTrue is false
Attempts:
2 left
💡 Hint
Look at what the fake database's saveUser method returns.
❓ assertion
intermediate
2:00remaining
Correct assertion for a fake object interaction
You have a fake object that records how many times a method was called. Which assertion correctly verifies that the method was called exactly 3 times?
JUnit
class FakeLogger {
    private int callCount = 0;
    public void log(String message) {
        callCount++;
    }
    public int getCallCount() {
        return callCount;
    }
}

@org.junit.Test
public void testLogging() {
    FakeLogger logger = new FakeLogger();
    logger.log("start");
    logger.log("process");
    logger.log("end");
    // Which assertion is correct here?
    org.junit.Assert.assertEquals(3, logger.getCallCount());
}
AassertEquals(3, logger.getCallCount());
BassertTrue(logger.getCallCount() > 3);
CassertFalse(logger.getCallCount() == 3);
DassertNull(logger.getCallCount());
Attempts:
2 left
💡 Hint
Check the exact number of times the log method was called.
🔧 Debug
advanced
2:00remaining
Identify the bug in this fake object usage
This JUnit test uses a fake object to simulate a payment gateway. The test always fails with a NullPointerException. What is the cause?
JUnit
class FakePaymentGateway implements PaymentGateway {
    public boolean processPayment(double amount) {
        return true;
    }
}

@org.junit.Test
public void testPayment() {
    PaymentService service = new PaymentService(null);
    boolean success = service.pay(100.0);
    org.junit.Assert.assertTrue(success);
}

interface PaymentGateway {
    boolean processPayment(double amount);
}

class PaymentService {
    private PaymentGateway gateway;
    public PaymentService(PaymentGateway gateway) {
        this.gateway = gateway;
    }
    public boolean pay(double amount) {
        return gateway.processPayment(amount);
    }
}
AThe PaymentGateway interface is missing the processPayment method
BThe fake object does not implement the processPayment method
CThe test assertion is incorrect and causes the failure
DThe PaymentService is created with null instead of the fake object
Attempts:
2 left
💡 Hint
Check what object is passed to PaymentService constructor.
🧠 Conceptual
advanced
1:30remaining
Purpose of fake objects in unit testing
Which statement best describes the main purpose of using fake objects in unit testing?
ATo replace real dependencies with simplified implementations for controlled testing
BTo automatically generate test cases without writing code
CTo measure the performance of the real system under load
DTo permanently store test data in a database
Attempts:
2 left
💡 Hint
Think about why we avoid using real dependencies in unit tests.
❓ framework
expert
2:30remaining
Using a fake object with JUnit and Mockito
Given the following JUnit test using Mockito, what will be the output of the assertion?
JUnit
import static org.mockito.Mockito.*;
import org.junit.Test;
import static org.junit.Assert.*;

public class OrderServiceTest {
    @Test
    public void testOrderProcessing() {
        PaymentGateway fakeGateway = mock(PaymentGateway.class);
        when(fakeGateway.processPayment(anyDouble())).thenReturn(false);

        OrderService service = new OrderService(fakeGateway);
        boolean result = service.placeOrder(50.0);

        assertFalse(result);
    }
}

interface PaymentGateway {
    boolean processPayment(double amount);
}

class OrderService {
    private final PaymentGateway gateway;
    public OrderService(PaymentGateway gateway) {
        this.gateway = gateway;
    }
    public boolean placeOrder(double amount) {
        return gateway.processPayment(amount);
    }
}
ATest fails with NullPointerException due to uninitialized mock
BTest fails because the fake returns true but assertion expects false
CTest passes because the fake returns false and assertFalse matches
DTest fails with AssertionError because assertFalse is true
Attempts:
2 left
💡 Hint
Check what the mock is configured to return and what the assertion expects.

Practice

(1/5)
1. What is the main purpose of using a fake object in JUnit testing?
easy
A. To replace a real component with a simple version for controlled testing
B. To speed up the compilation of test classes
C. To generate random test data automatically
D. To log test execution details to a file

Solution

  1. Step 1: Understand the role of fake objects

    Fake objects are simplified versions of real components used in tests to isolate the code under test.
  2. Step 2: Identify the main purpose

    The main purpose is to replace real parts that might be slow, unavailable, or unpredictable with controlled versions.
  3. Final Answer:

    To replace a real component with a simple version for controlled testing -> Option A
  4. Quick Check:

    Fake objects replace real parts for testing [OK]
Hint: Fake objects replace real parts with simple versions [OK]
Common Mistakes:
  • Confusing fake objects with mocks or stubs
  • Thinking fake objects generate random data
  • Assuming fake objects speed up compilation
2. Which of the following is the correct way to define a fake object class in Java implementing an interface DataService?
easy
A. public class FakeDataService { int getData() { return 42; } }
B. public class FakeDataService extends DataService { public int getData() { return 42; } }
C. public class FakeDataService implements DataService { public int getData() { return 42; } }
D. public interface FakeDataService implements DataService { int getData(); }

Solution

  1. Step 1: Recall Java syntax for implementing interfaces

    In Java, a class implements an interface using the implements keyword and must provide method implementations.
  2. Step 2: Check each option

    public class FakeDataService implements DataService { public int getData() { return 42; } } correctly uses implements and defines the method. public class FakeDataService extends DataService { public int getData() { return 42; } } incorrectly uses extends with an interface. public interface FakeDataService implements DataService { int getData(); } wrongly declares an interface implementing another interface with method body. public class FakeDataService { int getData() { return 42; } } lacks interface implementation.
  3. Final Answer:

    public class FakeDataService implements DataService { public int getData() { return 42; } } -> Option C
  4. Quick Check:

    Class implements interface with 'implements' keyword [OK]
Hint: Use 'implements' keyword to define fake class for interface [OK]
Common Mistakes:
  • Using 'extends' instead of 'implements' for interfaces
  • Defining interface instead of class for fake
  • Omitting method implementation in fake class
3. Given the following fake object and test code, what will be the output of the assertion?
interface Calculator { int add(int a, int b); }
class FakeCalculator implements Calculator {
  public int add(int a, int b) { return 10; }
}

@Test
void testAdd() {
  Calculator calc = new FakeCalculator();
  assertEquals(10, calc.add(3, 7));
}
medium
A. Runtime exception due to wrong method signature
B. Test fails because 3 + 7 is 10
C. Compilation error due to missing override annotation
D. Test passes because fake returns fixed 10

Solution

  1. Step 1: Analyze the fake object's method

    The add method in FakeCalculator always returns 10 regardless of inputs.
  2. Step 2: Check the assertion in the test

    The test asserts that calc.add(3, 7) equals 10, which matches the fake's return value.
  3. Final Answer:

    Test passes because fake returns fixed 10 -> Option D
  4. Quick Check:

    Fake returns fixed value matching assertion [OK]
Hint: Fake returns fixed value; assertion matches it [OK]
Common Mistakes:
  • Expecting real addition instead of fake's fixed return
  • Confusing compilation errors with missing annotations
  • Assuming runtime exceptions without cause
4. Identify the error in this fake object implementation:
interface UserRepository {
  String findUserName(int id);
}

class FakeUserRepository implements UserRepository {
  public String findUserName() {
    return "TestUser";
  }
}
medium
A. Method signature does not match interface method
B. Class should be abstract to implement interface
C. Return type String is incorrect
D. Interface cannot be implemented by a class

Solution

  1. Step 1: Compare method signatures

    The interface method findUserName requires an int id parameter, but the fake method has no parameters.
  2. Step 2: Understand Java interface implementation rules

    Implementing classes must match method signatures exactly, including parameters.
  3. Final Answer:

    Method signature does not match interface method -> Option A
  4. Quick Check:

    Method signatures must match interface exactly [OK]
Hint: Check method parameters match interface exactly [OK]
Common Mistakes:
  • Ignoring method parameters in fake implementation
  • Thinking return type mismatch is the error
  • Believing class must be abstract to implement interface
5. You want to test a service that depends on a slow external API. Which approach best uses a fake object to improve test speed and reliability?
hard
A. Use the real API client but add delays in the test to wait for responses
B. Create a fake API client implementing the same interface that returns fixed test data instantly
C. Mock the API client to throw exceptions randomly during tests
D. Remove the API client dependency from the service code

Solution

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

    The real API is slow and unreliable for tests, causing delays and flakiness.
  2. Step 2: Choose a fake object approach

    Creating a fake client that implements the same interface and returns fixed data instantly isolates the service and speeds tests.
  3. Step 3: Evaluate other options

    Use the real API client but add delays in the test to wait for responses slows tests further. Mock the API client to throw exceptions randomly during tests adds randomness, reducing reliability. Remove the API client dependency from the service code breaks service functionality.
  4. Final Answer:

    Create a fake API client implementing the same interface that returns fixed test data instantly -> Option B
  5. Quick Check:

    Fake replaces slow API with fast fixed data [OK]
Hint: Fake slow dependencies with fast fixed-return objects [OK]
Common Mistakes:
  • Adding delays instead of faking slow parts
  • Using mocks to add randomness in tests
  • Removing dependencies instead of faking them
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