Patterncore
Service stub
Also called Service Stub, stub service, service virtualization.
A service stub replaces a slow, remote or unfinished service with a local implementation of the same interface that gives canned answers, so tests and development do not depend on the service.
- Family
- architectural
- Intent
- Remove the dependence on problematic services during testing.
Intent
A service stub "Removes dependence upon problematic services during testing."1 The code uses the service through an interface. In tests, a stub implements the interface with canned answers, and the real service is not called.
Problem
Enterprise systems often use services of other organizations. The catalog names "credit scoring, tax rate lookups, and pricing engines".1 These services are often remote, so they can be slow or not available, and some of them are not finished when the program is written.
When the tests call the real service, they are slow, and they fail when the service fails. The catalog says that such dependencies "will lead to times when tests can't execute. When tests can't run the development process is broken."1
Solution
"Replacing the service during testing with a Service Stub that runs locally, fast, and in memory improves your development experience."1 The parts are:
- The interface. The code calls the service through a Separated interface, usually behind a Gateway.
- The real implementation. It calls the remote service.
- The stub. It implements the same interface and gives simple, canned answers, such as a flat tax rate or a small table of rates. It has as little logic as possible.
- The choice. The test, a Plugin configuration or Dependency injection gives the code the stub or the real implementation.
BillingService --uses--> TaxService
^ ^
RemoteTaxService TaxServiceStub
(network, slow) (in memory, canned rates)
In the following program, a test checks the total of a bill with a stub that gives a flat rate.
class FlatRateTaxStub: # runs locally, fast and in memory
def __init__(self, rate_bp):
self.rate_bp = rate_bp
def rate_bp_for(self, region):
return self.rate_bp
def total_cents(amount_cents, region, taxes):
return amount_cents + amount_cents * taxes.rate_bp_for(region) // 10000
assert total_cents(10000, "north", FlatRateTaxStub(650)) == 10650
assert total_cents(10000, "north", FlatRateTaxStub(0)) == 10000
print("the tests pass with no network")
the tests pass with no network
Example
Each example has a TaxService interface that gives a tax rate in basis points, so 650 is 6.5%. RemoteTaxService stands for the real service, which is not reachable. TaxServiceStub has canned rates for two regions and a default rate for the others, and counts its calls. BillingService adds the tax to an amount. The program first tries the real service and gets an error. Then it bills 100.00 in three regions with the stub, and prints the number of calls that the stub got.
from typing import Protocol
class TaxService(Protocol):
def rate_bp(self, region: str) -> int: ... # the rate in basis points: 650 is 6.5%
class RemoteTaxService:
"""The real service. Here it stands for a remote call that is not reachable."""
def rate_bp(self, region):
raise ConnectionError("the tax service is not reachable")
class TaxServiceStub:
"""Runs locally, fast and in memory, with canned rates."""
RATES = {"north": 650, "south": 0}
def __init__(self):
self.calls = 0
def rate_bp(self, region):
self.calls += 1
return self.RATES.get(region, 500) # a default rate for the other regions
class BillingService:
def __init__(self, taxes: TaxService):
self.taxes = taxes
def total_cents(self, amount_cents, region):
return amount_cents + amount_cents * self.taxes.rate_bp(region) // 10000
def money(cents):
return f"{cents // 100}.{cents % 100:02d}"
try:
BillingService(RemoteTaxService()).total_cents(10000, "north")
except ConnectionError as e:
print("real service: error:", e)
stub = TaxServiceStub()
billing = BillingService(stub)
for region in ["north", "south", "east"]:
print(f"{region}: 100.00 with tax is {money(billing.total_cents(10000, region))}")
print("the stub got", stub.calls, "calls")
real service: error: the tax service is not reachable
north: 100.00 with tax is 106.50
south: 100.00 with tax is 100.00
east: 100.00 with tax is 105.00
the stub got 3 calls
- Verdict: idiom.
TaxServiceis atyping.Protocol, so the stub and the real service need no common base class.BillingServicegets the service in its constructor, and the program or the test chooses which one. - The stub counts its calls, so a test can also check how the code uses the service.
import java.util.List;
import java.util.Map;
public class Main {
interface TaxService {
long rateBp(String region); // the rate in basis points: 650 is 6.5%
}
static class ServiceUnavailable extends RuntimeException {
ServiceUnavailable(String m) { super(m); }
}
// The real service. Here it stands for a remote call that is not reachable.
static class RemoteTaxService implements TaxService {
public long rateBp(String region) {
throw new ServiceUnavailable("the tax service is not reachable");
}
}
// Runs locally, fast and in memory, with canned rates.
static class TaxServiceStub implements TaxService {
static final Map<String, Long> RATES = Map.of("north", 650L, "south", 0L);
int calls = 0;
public long rateBp(String region) {
calls++;
return RATES.getOrDefault(region, 500L); // a default rate for the other regions
}
}
static class BillingService {
private final TaxService taxes;
BillingService(TaxService taxes) { this.taxes = taxes; }
long totalCents(long amountCents, String region) {
return amountCents + amountCents * taxes.rateBp(region) / 10000;
}
}
static String money(long c) { return String.format("%d.%02d", c / 100, c % 100); }
public static void main(String[] args) {
try {
new BillingService(new RemoteTaxService()).totalCents(10000, "north");
} catch (ServiceUnavailable e) {
System.out.println("real service: error: " + e.getMessage());
}
TaxServiceStub stub = new TaxServiceStub();
BillingService billing = new BillingService(stub);
for (String region : List.of("north", "south", "east")) {
System.out.println(region + ": 100.00 with tax is " + money(billing.totalCents(10000, region)));
}
System.out.println("the stub got " + stub.calls + " calls");
}
}
real service: error: the tax service is not reachable
north: 100.00 with tax is 106.50
south: 100.00 with tax is 100.00
east: 100.00 with tax is 105.00
the stub got 3 calls
- Verdict: idiom.
TaxServiceis an interface, and the stub and the real service implement it. Mocking libraries such as Mockito can make such a stub at run time, but a small class like this one is easy to read.
// The TaxService interface: rateBp(region) gives the rate in basis points; 650 is 6.5%.
// The real service. Here it stands for a remote call that is not reachable.
class RemoteTaxService {
rateBp(region) {
throw new Error("the tax service is not reachable");
}
}
// Runs locally, fast and in memory, with canned rates.
class TaxServiceStub {
static RATES = new Map([
["north", 650],
["south", 0],
]);
calls = 0;
rateBp(region) {
this.calls++;
return TaxServiceStub.RATES.get(region) ?? 500; // a default rate for the other regions
}
}
class BillingService {
constructor(taxes) {
this.taxes = taxes;
}
totalCents(amountCents, region) {
return amountCents + Math.floor((amountCents * this.taxes.rateBp(region)) / 10000);
}
}
const money = (c) => `${Math.floor(c / 100)}.${String(c % 100).padStart(2, "0")}`;
try {
new BillingService(new RemoteTaxService()).totalCents(10000, "north");
} catch (e) {
console.log("real service: error:", e.message);
}
const stub = new TaxServiceStub();
const billing = new BillingService(stub);
for (const region of ["north", "south", "east"]) {
console.log(`${region}: 100.00 with tax is ${money(billing.totalCents(10000, region))}`);
}
console.log("the stub got", stub.calls, "calls");
real service: error: the tax service is not reachable
north: 100.00 with tax is 106.50
south: 100.00 with tax is 100.00
east: 100.00 with tax is 105.00
the stub got 3 calls
- Verdict: idiom. Any object with a
rateBpmethod can be the tax service, so the stub needs no common class.??gives the default rate only when the region is not in the map, and keeps the rate 0 of the south.
package main
import (
"errors"
"fmt"
)
// TaxService gives the rate in basis points: 650 is 6.5%.
type TaxService interface {
RateBp(region string) (int64, error)
}
// RemoteTaxService is the real service. Here it stands for a remote call that is not reachable.
type RemoteTaxService struct{}
func (RemoteTaxService) RateBp(string) (int64, error) {
return 0, errors.New("the tax service is not reachable")
}
// TaxServiceStub runs locally, fast and in memory, with canned rates.
type TaxServiceStub struct{ calls int }
var stubRates = map[string]int64{"north": 650, "south": 0}
func (s *TaxServiceStub) RateBp(region string) (int64, error) {
s.calls++
if r, ok := stubRates[region]; ok {
return r, nil
}
return 500, nil // a default rate for the other regions
}
type BillingService struct{ taxes TaxService }
func (b BillingService) TotalCents(amount int64, region string) (int64, error) {
r, err := b.taxes.RateBp(region)
if err != nil {
return 0, err
}
return amount + amount*r/10000, nil
}
func money(c int64) string { return fmt.Sprintf("%d.%02d", c/100, c%100) }
func main() {
if _, err := (BillingService{RemoteTaxService{}}).TotalCents(10000, "north"); err != nil {
fmt.Println("real service: error:", err)
}
stub := &TaxServiceStub{}
billing := BillingService{stub}
for _, region := range []string{"north", "south", "east"} {
t, _ := billing.TotalCents(10000, region)
fmt.Printf("%s: 100.00 with tax is %s\n", region, money(t))
}
fmt.Println("the stub got", stub.calls, "calls")
}
real service: error: the tax service is not reachable
north: 100.00 with tax is 106.50
south: 100.00 with tax is 100.00
east: 100.00 with tax is 105.00
the stub got 3 calls
- Verdict: idiom.
TaxServiceis an interface that the stub satisfies by its method set. The stub has a pointer receiver, so the program can readcallsafter the calls. - The
net/http/httptestpackage can run a stub HTTP server in the test process, for code that calls a service over HTTP.
use std::cell::Cell;
// The rate in basis points: 650 is 6.5%.
trait TaxService {
fn rate_bp(&self, region: &str) -> Result<i64, String>;
}
// The real service. Here it stands for a remote call that is not reachable.
struct RemoteTaxService;
impl TaxService for RemoteTaxService {
fn rate_bp(&self, _region: &str) -> Result<i64, String> {
Err("the tax service is not reachable".to_string())
}
}
// Runs locally, fast and in memory, with canned rates.
#[derive(Default)]
struct TaxServiceStub {
calls: Cell<u32>,
}
impl TaxService for TaxServiceStub {
fn rate_bp(&self, region: &str) -> Result<i64, String> {
self.calls.set(self.calls.get() + 1);
Ok(match region {
"north" => 650,
"south" => 0,
_ => 500, // a default rate for the other regions
})
}
}
struct BillingService<'a> {
taxes: &'a dyn TaxService,
}
impl BillingService<'_> {
fn total_cents(&self, amount: i64, region: &str) -> Result<i64, String> {
Ok(amount + amount * self.taxes.rate_bp(region)? / 10000)
}
}
fn money(c: i64) -> String {
format!("{}.{:02}", c / 100, c % 100)
}
fn main() {
if let Err(e) = (BillingService { taxes: &RemoteTaxService }).total_cents(10000, "north") {
println!("real service: error: {}", e);
}
let stub = TaxServiceStub::default();
let billing = BillingService { taxes: &stub };
for region in ["north", "south", "east"] {
println!("{}: 100.00 with tax is {}", region, money(billing.total_cents(10000, region).unwrap()));
}
println!("the stub got {} calls", stub.calls.get());
}
real service: error: the tax service is not reachable
north: 100.00 with tax is 106.50
south: 100.00 with tax is 100.00
east: 100.00 with tax is 105.00
the stub got 3 calls
- Verdict: idiom.
TaxServiceis a trait, andBillingServicekeeps a&dyn TaxService. The stub counts its calls in aCell, because the trait method takes&self.
Consequences
Benefits.
- Fast and reliable tests. The tests do not wait for the network and do not fail when the service fails.
- Work before the service is ready. The team can write and test the code while the other team finishes the service.
- Cases that are hard to make. A stub can give an answer that the real service seldom gives, such as an error or a rate of zero.
Liabilities.
A stub can stop matching the real service. In the following program, the real service changed the unit of its rate, but the stub still gives the old unit. The tests with the stub pass, and the bill in production is wrong.
This code runs but gives a wrong answer on purpose.
def total_cents(amount_cents, rate_bp): # the code expects basis points: 650 is 6.5%
return amount_cents + amount_cents * rate_bp // 10000
class TaxServiceStub:
def rate(self, region):
return 650 # basis points, as the service once returned
class RemoteTaxService: # the real service changed: it now returns tenths of a percent
def rate(self, region):
return 65
print("with the stub:", total_cents(10000, TaxServiceStub().rate("north")))
print("in production:", total_cents(10000, RemoteTaxService().rate("north")))
with the stub: 10650
in production: 10065
Run contract tests against the real service from time to time. Fowler writes that contract tests "check that all the calls against your test doubles return the same results as a call to the external service would".2 When a contract test fails, update the stub and the code.
The real calls are not tested. Tests with the stub do not check the network code, the encoding or the errors of the real service. These need their own integration tests.
A stub can grow. A stub with much logic becomes a second implementation of the service, with its own bugs. Keep it simple.
When not to use it
When the service is fast, local and reliable. If the tests can call it with no problem, they test more with the real service.
When the test must check the conversation with the service. If the test must check which calls the code makes and in which order, use a mock object, which checks the calls. A stub only answers them.
Variants and related patterns
Test doubles. A service stub is a kind of Test double. Fowler's description of the kinds says: "Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test."3 A fake has a working implementation with a shortcut, such as a database in memory.3
HTTP stubs. A stub can also be a local server that answers HTTP requests. WireMock gives "HTTP response stubbing, matchable on URL, header and body content patterns".4 The code under test then needs no change, only another address of the service.
Related patterns. A Gateway behind a Separated interface gives the place to put the stub. A Plugin chooses the stub in the test configuration. The book shows a tax service with a flat rate stub.5 A Null Object is like a stub that does nothing, but it is part of the program and not only of the tests.
Known uses
- WireMock runs HTTP stubs "in unit tests, as a standalone process or as a WAR app" and can record and play back stubs.4
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Service Stub, pattern summary, by David Rice
- Martin Fowler, ContractTest, bliki, 12 January 2011, whole article
- Martin Fowler, TestDouble, bliki, the kinds of double
- WireMock documentation, Overview, Key features
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Service Stub
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag PHAADS Edit this page History Report an error Markdown