0
0
JUnittesting~5 mins

Stub objects in JUnit

Choose your learning style9 modes available
Introduction

Stub objects help us test parts of a program by pretending to be other parts. They give fixed answers so we can focus on what we want to test.

When the real part is not ready yet but you want to test your code.
When the real part is slow or hard to use during tests.
When you want to control the answers from a part to test different situations.
When the real part depends on things outside your control, like a database or web service.
Syntax
JUnit
class StubClass implements Interface {
    @Override
    public ReturnType methodName() {
        return fixedValue;
    }
}

Stub classes implement the same interface as the real class.

Methods return fixed values to simulate behavior.

Examples
This stub always returns 5 for add, no matter the inputs.
JUnit
class StubCalculator implements Calculator {
    @Override
    public int add(int a, int b) {
        return 5; // always returns 5
    }
}
This stub returns a fixed user object for any id.
JUnit
class StubUserService implements UserService {
    @Override
    public User getUserById(int id) {
        return new User("TestUser", 123);
    }
}
Sample Program

This test uses a stub calculator that always returns 5 for add. The test checks that the stub returns 5 as expected.

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

interface Calculator {
    int add(int a, int b);
}

class StubCalculator implements Calculator {
    @Override
    public int add(int a, int b) {
        return 5; // fixed answer
    }
}

public class CalculatorTest {
    @Test
    void testAddWithStub() {
        Calculator calc = new StubCalculator();
        int result = calc.add(2, 3);
        assertEquals(5, result, "Stub should return fixed value 5");
    }
}
OutputSuccess
Important Notes

Stubs are simple and return fixed data to help isolate tests.

They are different from mocks, which also check how they are used.

Use stubs to avoid slow or unreliable parts during testing.

Summary

Stub objects replace real parts with fixed answers for testing.

They help test code in isolation and control test conditions.

Stubs are easy to write and useful when real parts are unavailable or slow.