0
0
JUnittesting~15 mins

Stub objects in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify calculation method using a stub object
Preconditions (2)
Step 1: Create a stub object that returns a fixed multiplier value of 5
Step 2: Inject the stub object into the Calculator class
Step 3: Call the calculate method with input value 10
Step 4: Observe the returned result
✅ Expected Result: The calculate method returns 50 (10 multiplied by 5 from the stub)
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the calculate method returns 50 when input is 10
Best Practices:
Use stub objects to isolate the unit under test
Keep stub implementation simple and focused
Use dependency injection to provide the stub
Use clear and descriptive test method names
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

interface MultiplierService {
    int getMultiplier();
}

class Calculator {
    private final MultiplierService multiplierService;

    public Calculator(MultiplierService multiplierService) {
        this.multiplierService = multiplierService;
    }

    public int calculate(int input) {
        return input * multiplierService.getMultiplier();
    }
}

public class CalculatorTest {

    // Stub object that returns fixed multiplier 5
    static class MultiplierServiceStub implements MultiplierService {
        @Override
        public int getMultiplier() {
            return 5;
        }
    }

    @Test
    void calculate_returnsCorrectResult_usingStub() {
        MultiplierService stub = new MultiplierServiceStub();
        Calculator calculator = new Calculator(stub);

        int result = calculator.calculate(10);

        assertEquals(50, result, "Calculator should return input multiplied by stub multiplier");
    }
}

This test uses a stub object MultiplierServiceStub that always returns 5 as the multiplier. We inject this stub into the Calculator class to isolate the test from any real external service.

The test method calculate_returnsCorrectResult_usingStub calls calculate(10) and asserts the result is 50, which is 10 multiplied by the stub's fixed multiplier 5.

This approach ensures the test is fast, reliable, and focused only on the Calculator logic, not on external dependencies.

Common Mistakes - 3 Pitfalls
Not using dependency injection and creating the stub inside the class under test
Making the stub object too complex or replicating full service logic
Not asserting the expected result or using vague assertions
Bonus Challenge

Now add data-driven testing with 3 different input values and expected results using the stub

Show Hint