Verify calculation method using a stub object
Preconditions (2)
✅ Expected Result: The calculate method returns 50 (10 multiplied by 5 from the stub)
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.
Now add data-driven testing with 3 different input values and expected results using the stub
stub object in JUnit testing?getValue() to return 5. Options A, C, and D have invalid Java syntax.testService.getValue()?
class TestService {
int getValue() { return 0; }
}
TestService testService = new TestService() {
@Override
int getValue() { return 10; }
};
System.out.println(testService.getValue());getValue() to return 10 instead of 0.testService.getValue() invokes the overridden method, so it returns 10.MyService service = new MyService() {
public int getValue() {
return "five";
}
};getValue() is declared to return int, but returns a String "five".Pass the test and this pattern moves unknown