Whether you're just getting started with unit testing or looking to refine your understanding of testing techniques, this blog will explain what stubs in programming are, why they matter, and how to use them effectively in your codebase.
What Are Stubs?
In programming, a stub is a piece of code that stands in for another component, usually to simulate its behavior in a simplified way.
Stubs are used during testing to provide predetermined responses to method calls. They help you isolate the behavior of a unit (like a function or class) by replacing real dependencies that may be hard to include in tests—such as databases, APIs, or third-party services.
In short, stubs help you answer this question:
“What if I could control this part of the system so I could focus only on testing my logic?”
Why Use Stubs?
Imagine you’re building an application that fetches weather data from a remote API. You want to test the function that converts temperature units, but this function depends on a live API call. This creates several problems:
- The API might be slow or unavailable.
- Your test could fail due to network issues—not code bugs.
- You may be rate-limited or charged for requests.
Using a stub, you can bypass the real API call and simulate a response instead.
Stubs help with:
- Isolation: Testing only the code you care about.
- Speed: No real I/O operations = faster tests.
- Control: Predictable behavior and test results.
- Reliability: Tests don’t break due to external systems.
Stubs vs. Mocks: What's the Difference?
These terms are often confused, so let’s clarify:
Feature | Stub | Mock |
Primary Purpose | Provide predefined responses | Verify behavior (method calls, inputs) |
Focus | Data setup | Interaction checking |
Complexity | Simple | More advanced |
Example:
- A stub returns a fake temperature from an API.
- A mock verifies that your code called the API exactly once with the right parameters.
In many frameworks, the line between stubs and mocks is blurred. Tools like Mockito, Sinon.js, or unittest.mock in Python provide both.
Example: Using a Stub in JavaScript
Let’s look at a basic stub in JavaScript using plain code (no libraries).
function getUserName(apiClient, userId) {
return apiClient.getUser(userId).name;
}
// Stub
const fakeApiClient = {
getUser: function(id) {
return { id: id, name: "Alice" };
}
};
// Test
console.log(getUserName(fakeApiClient, 123)); // Output: Alice
In this test, we replaced the real apiClient with a stub that returns a fixed user object.
Using Stubs in Java with Mockito
In Java, you can use Mockito to create stubs easily.
import static org.mockito.Mockito.*;
@Test
public void testGetUserName() {
ApiClient apiClient = mock(ApiClient.class);
when(apiClient.getUser(123)).thenReturn(new User(123, "Alice"));
UserService service = new UserService(apiClient);
String result = service.getUserName(123);
assertEquals("Alice", result);
}
Here, when(...).thenReturn(...) is used to stub the method call.
Benefits of Using Stubs
- Faster Tests: Avoid waiting on network, database, or disk.
- Deterministic: Results don’t change unexpectedly.
- Isolated: Focus only on the logic you're testing.
- No External Dependencies: Great for continuous integration environments.
When Should You Use Stubs?
Use stubs when:
- The real implementation is unavailable, unstable, or slow.
- You want to test edge cases (e.g., what happens if the API returns an error).
- You need predictable and fast test runs.
- You’re testing early in development before some components are built.
Limitations of Stubs
- Not Realistic: Since they don’t use real data, they might miss integration issues.
- Maintenance Overhead: Fake responses must be updated if APIs change.
- Overuse: Relying too much on stubs can give a false sense of security.
That’s why unit tests with stubs should be complemented with integration and end-to-end tests.
Final Thoughts
Stubs are one of the simplest yet most powerful tools in a developer's testing toolkit. They help you isolate and test your code under controlled conditions, making it easier to identify bugs and verify logic.
Whether you're testing a function that makes an API call or simulating database access in a service, stubs give you the flexibility to build faster, more reliable, and maintainable test suites.
Understanding when and how to use stubs effectively is a skill that will pay off throughout your software engineering career.
Read more on- https://keploy.io/docs/concepts/reference/glossary/stubs/