Mocking Commands During Script Tests

Su Suriya Ravichandran Updated 06 Dec 2026
16 min read ·Lesson 186 of 205

Most useful Bash scripts are glue: they call other programs. A monitoring script calls curl, a deployment script calls git and systemctl, a backup script calls rsync and mysqldump. Testing such scripts by letting them call the real programs is slow, unreliable and sometimes dangerous. The test would need a running web server, a network connection, root rights and a real service to restart, and a mistake in the script could restart a production service or delete real data.

Mocking solves this by replacing the external commands with fakes during the test. A fake, also called a mock or stub, is a small program with the same name as the real command. It does not do the real work; instead it records how it was called and returns whatever result the test asks for: success, a specific failure, or a prepared output. The test can then check two things: that the script reacts correctly to each result, and that it called the commands with the right arguments.

This lesson explains how Bash finds commands and why that makes mocking possible, shows the three common mocking techniques, builds a small reusable mock library for Bats (lesson 185), and uses it to test a script that checks a website and restarts its service.

How Bash Finds a Command

When a script runs curl https://example.com, Bash looks for something called curl in a fixed order (lesson 183): an alias (only in interactive shells), then a shell function, then a built-in command, and finally an executable file in one of the directories listed in the PATH variable, searched from left to right. The first match wins.

Every one of these lookup steps is a place where a test can insert a fake:

  • A directory at the front of PATH: an executable file named curl in that directory is found before /usr/bin/curl.
  • A shell function named curl: functions are found before files in PATH.
  • A variable holding the command name, such as "$CURL": the test sets the variable to a fake.

The first technique works for almost any script without changing it, so it is the main technique of this lesson.

Technique 1: Fake Programs in PATH

The idea is simple: create a temporary directory, write a small executable script named after the command into it, and put the directory first in PATH. Every call of that command by the script under test, and by any program it starts, now reaches the fake:

mkdir -p /tmp/mk
printf '#!/bin/sh\necho "fake curl"\n' > /tmp/mk/curl
chmod +x /tmp/mk/curl
PATH=/tmp/mk:$PATH

curl x
type -a curl
fake curl
curl is /tmp/mk/curl
curl is /usr/bin/curl
curl is /bin/curl

type -a lists all the places where curl was found, in search order: the fake comes first and hides the real program. The fake must have a shebang line and be executable, because it is started like any other program. It can be written in any language; Bash is the natural choice.

Limits of PATH Fakes

A fake in PATH cannot replace everything:

  • Absolute paths bypass PATH. If the script calls /usr/bin/curl, Bash runs that exact file and never looks at PATH:
$ /usr/bin/curl -sS http://shop.test/
curl: (6) Could not resolve host: shop.test

This is one reason why scripts should call commands by name. If a script must use absolute paths, it can read them from variables, which leads to technique 3. Three more limits apply:

  • Built-in commands cannot be replaced by files. echo, printf, read, cd and test are built into Bash and found before PATH is searched. They rarely need to be faked; when they must, a function can override them.

  • The fakes need some real commands themselves. The fakes in this lesson use dirname, wc, sed, tail and cat to do their bookkeeping. Faking one of these would break the other fakes, so either avoid faking basic tools or write fakes that call them by absolute path.

  • The hash table. An interactive shell that already ran curl remembers its location (lesson 183). Tests start fresh processes, so this rarely matters, but if a fake seems to be ignored in a long-running shell, hash -r clears the memory.

Technique 2: Function Overrides

A shell function with the name of a command replaces that command for the shell that defines it. With export -f, Bash also passes the function to child Bash processes through the environment, so a script started from the test sees it too:

curl() { echo "fake curl: $*" >&2; return 0; }
export -f curl
./reach.sh http://shop.test/
unset -f curl
./reach.sh http://shop.test/; echo "status $?"
fake curl: --silent http://shop.test/
reachable
status 6

reach.sh is a two-line script that runs curl --silent "$1" && echo "reachable". With the exported function, it called the fake and reported success; after unset -f curl, it reached the real curl, which failed with status 6 because the host does not exist.

Function overrides are convenient for unit tests of functions loaded with source, where the code under test runs in the same shell as the test. Exported functions have two limits: only Bash scripts receive them, so a program written in another language, or a script started with sh, still calls the real command; and they are invisible in the file system, which makes them harder to inspect when something goes wrong. Fakes in PATH work for every kind of program.

Technique 3: Commands in Variables

A script can take the commands it calls from variables with defaults:

CURL=${CURL:-curl}
"$CURL" --fail "$url"

A test then runs the script with CURL=/path/to/fake. This makes the dependency explicit and also works for absolute paths, at the cost of slightly less readable scripts. It is most useful for commands whose location really varies between systems, and for scripts that deliberately use absolute paths for security reasons.

What Makes a Good Fake

Whichever technique delivers it, a fake has three jobs:

  1. Record each call, including all arguments, so the test can check how the command was used.
  2. Return a controllable result: an exit status chosen by the test, and optionally prepared output.
  3. Support sequences, because many scripts call the same command several times and react to changing results: a retry loop needs curl to fail twice and then succeed.

Recording arguments correctly needs care. Writing $* to the log joins all arguments with spaces, so the calls cmd "two words" and cmd two words would look identical. printf '%q ' writes each argument in Bash's quoted form instead, which keeps the boundaries visible:

printf '%q ' --output /dev/null "two words" 'a$b'; echo
--output /dev/null two\ words a\$b

Ordinary arguments appear unchanged, so the recorded calls stay readable, while spaces and special characters are escaped.

A Reusable Mock Library for Bats

The following helper file collects these ideas into four functions. It lives next to the tests as test/mocks.bash and is loaded in a test file with load mocks:

# mocks.bash - replace external commands with recording fakes in Bats tests
#
# mock_setup                      create the mock directory and put it first in PATH
# mock CMD [STATUS...]            fake CMD; each call exits with the next STATUS (the last repeats)
# mock_output CMD TEXT            the fake CMD also prints TEXT on every call
# mock_calls CMD                  print the recorded calls of CMD, one line per call

mock_setup() {
    MOCK_DIR="$BATS_TEST_TMPDIR/mocks"
    mkdir -p "$MOCK_DIR"
    PATH="$MOCK_DIR:$PATH"
}

mock() {
    local cmd=$1
    shift
    printf '%s\n' "${@:-0}" > "$MOCK_DIR/$cmd.statuses"
    : > "$MOCK_DIR/$cmd.calls"
    cat > "$MOCK_DIR/$cmd" <<STUB
#!/usr/bin/env bash
# fake $cmd created by mocks.bash
dir=\$(dirname "\$0")
args=\$(printf '%q ' "\$@")                  # quote each argument, keep boundaries
printf '%s\n' "\${args% }" >> "\$dir/$cmd.calls"
[[ -f "\$dir/$cmd.output" ]] && cat "\$dir/$cmd.output"
n=\$(wc -l < "\$dir/$cmd.calls")
status=\$(sed -n "\${n}p" "\$dir/$cmd.statuses")
exit "\${status:-\$(tail -n 1 "\$dir/$cmd.statuses")}"
STUB
    chmod +x "$MOCK_DIR/$cmd"
}

mock_output() {
    printf '%s\n' "$2" > "$MOCK_DIR/$1.output"
}

mock_calls() {
    cat "$MOCK_DIR/$1.calls"
}

How It Works

  • mock_setup creates a mocks directory inside the test's private temporary directory, $BATS_TEST_TMPDIR, and puts it first in PATH. Because Bats runs every test in its own process and deletes the temporary directory afterwards, fakes never leak from one test into another.
  • mock CMD STATUS... writes three files: CMD.statuses with one exit status per line, an empty call log CMD.calls, and the fake program CMD itself. "${@:-0}" uses the given statuses, or a single 0 if none were given, so mock sleep creates a fake that always succeeds.
  • The fake program is generated from a here document (lesson 63). The delimiter STUB is unquoted, so $cmd is replaced by the command's name while the fake is written; every $ that must stay in the fake is escaped as \$. For mock curl, the generated file starts like this:
#!/usr/bin/env bash
# fake curl created by mocks.bash
dir=$(dirname "$0")
args=$(printf '%q ' "$@")                  # quote each argument, keep boundaries
printf '%s\n' "${args% }" >> "$dir/curl.calls"
  • Status sequences. On each call, the fake first appends its arguments to the call log, then counts the lines in the log to find out which call this is, and takes the status from the same line of the statuses file. When the list is exhausted, sed prints nothing, and the fake falls back to the last status in the list. mock curl 7 7 7 0 therefore fails three times with status 7 (curl's "failed to connect") and succeeds on every later call; mock curl 22 fails on every call with status 22 (an HTTP error status with --fail).
  • Output. mock_output stores text that the fake prints on every call, for commands whose output the script uses.
  • mock_calls prints the call log, one line per call, in a form tests can compare with expected strings or count with wc -l.

The Script Under Test

check-site.sh checks a web application's health URL. If several attempts in a row fail, it restarts the application's systemd service and checks once more:

#!/usr/bin/env bash
#
# check-site.sh - check a web application and restart its service when it stays down
#
# Usage: check-site.sh URL SERVICE
#
# The URL is tried up to ATTEMPTS times (default 3), WAIT seconds apart (default 5).
# If every attempt fails, the systemd SERVICE is restarted and checked once more.
# Exit status: 0 healthy, 1 restarted but still failing or restart failed, 2 usage error

set -euo pipefail

ATTEMPTS=${ATTEMPTS:-3}
WAIT=${WAIT:-5}

log() { printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"; }

(( $# == 2 )) || { sed -n '5s/^# //p' "$0" >&2; exit 2; }
url=$1 service=$2

is_up() {
    curl --fail --silent --show-error --max-time 10 --output /dev/null "$url"
}

for (( i = 1; i <= ATTEMPTS; i++ )); do
    if is_up; then
        log "OK $url (attempt $i)"
        exit 0
    fi
    log "attempt $i of $ATTEMPTS failed"
    (( i < ATTEMPTS )) && sleep "$WAIT"
done

log "restarting $service"
if ! sudo systemctl restart "$service"; then
    log "ERROR: could not restart $service"
    exit 1
fi
sleep "$WAIT"
if is_up; then
    log "RECOVERED $url after restarting $service"
    exit 0
fi
log "ERROR: $url still down after restarting $service"
exit 1

Testing it for real would require a web server that can be made to fail on demand, permission to restart a service, and patience: a single run of the "stays down" case waits 15 seconds. Four commands make it hard to test, and each is replaced by a fake:

CommandProblem in testsFake behavior
curlneeds a server whose health the test controlsstatus sequence chosen per test
sudoneeds root rights; would restart a real servicerecords the call, succeeds or fails as asked
sleepmakes tests slowreturns immediately, records the duration
dateoutput changes every second, so lines cannot be compared exactlyprints a fixed timestamp

Faking sudo rather than systemctl is deliberate: the script calls sudo, which in turn would call systemctl. Replacing the outermost command keeps the test from ever needing administrator rights, and the recorded call systemctl restart shop still shows exactly what would have been executed.

A Complete Example: Testing check-site.sh

The test file creates the common fakes in setup and adds a curl fake with the right behavior in each test:

#!/usr/bin/env bats
#
# Tests for bin/check-site.sh. curl, sudo, sleep and date are replaced by fakes,
# so the tests need no network, no root rights and no waiting.

bats_require_minimum_version 1.5.0

setup() {
    load mocks
    mock_setup
    mock sleep                      # never wait
    mock sudo                       # never restart anything for real
    mock date
    mock_output date '2026-12-01 09:00:00'
    CHECK="$BATS_TEST_DIRNAME/../bin/check-site.sh"
    URL=http://shop.test/health
}

@test "a healthy site is reported once, without waiting or restarting" {
    mock curl 0
    run -0 "$CHECK" "$URL" shop
    [ "$output" = "2026-12-01 09:00:00 OK $URL (attempt 1)" ]
    [ -z "$(mock_calls sleep)" ]
    [ -z "$(mock_calls sudo)" ]
}

@test "curl is called with fail, timeout and the URL" {
    mock curl 0
    run -0 "$CHECK" "$URL" shop
    [ "$(mock_calls curl)" = "--fail --silent --show-error --max-time 10 --output /dev/null $URL" ]
}

@test "a short outage is retried after waiting" {
    mock curl 7 0                   # first call fails, second succeeds
    run -0 "$CHECK" "$URL" shop
    [ "${lines[0]}" = "2026-12-01 09:00:00 attempt 1 of 3 failed" ]
    [ "${lines[1]}" = "2026-12-01 09:00:00 OK $URL (attempt 2)" ]
    [ "$(mock_calls sleep)" = "5" ]
    [ -z "$(mock_calls sudo)" ]
}

@test "a site that stays down is restarted and checked again" {
    mock curl 7 7 7 0               # three failures, then healthy after the restart
    run -0 "$CHECK" "$URL" shop
    [ "$(mock_calls sudo)" = "systemctl restart shop" ]
    [ "$(mock_calls curl | wc -l)" -eq 4 ]
    [ "$(mock_calls sleep | wc -l)" -eq 3 ]
    [ "${lines[-1]}" = "2026-12-01 09:00:00 RECOVERED $URL after restarting shop" ]
}

@test "a site still down after the restart exits with status 1" {
    mock curl 22                    # every call fails
    run -1 "$CHECK" "$URL" shop
    [[ ${lines[-1]} == *"ERROR: $URL still down after restarting shop" ]]
}

@test "a failed restart exits with status 1 and skips the final check" {
    mock curl 7
    mock sudo 1
    run -1 "$CHECK" "$URL" shop
    [[ ${lines[-1]} == *"ERROR: could not restart shop" ]]
    [ "$(mock_calls curl | wc -l)" -eq 3 ]
}

@test "ATTEMPTS and WAIT can be changed through the environment" {
    mock curl 7
    ATTEMPTS=2 WAIT=1 run -1 "$CHECK" "$URL" shop
    [ "$(mock_calls sleep)" = $'1\n1' ]
}

@test "a missing argument is a usage error" {
    run -2 "$CHECK" "$URL"
    [[ $output == Usage:* ]]
}

What the Tests Check

  • Results and reactions. Each test sets up one situation through the curl fake's status sequence, from "healthy at once" to "down even after a restart", and checks the script's exit status and messages. Because date is fixed, whole lines can be compared exactly.
  • Interactions. The tests also check what the script did with the outside world: that a healthy site causes no restart (mock_calls sudo is empty), that a restart calls exactly systemctl restart shop, that curl is called with --fail and a timeout, and how often the script waited. These checks catch bugs that the output alone would not reveal, such as a script that prints "OK" but forgot --fail, which would make curl report success for an HTTP 500 response.
  • Counting calls. In the restart test, curl must run four times (three attempts plus the check after the restart) and sleep three times (two waits between attempts plus one after the restart). If the script failed to skip the wait after the last attempt, or forgot the final check, the counts would differ.
  • A negative path that must not happen. When the restart itself fails, the script must stop without checking again; the test verifies that curl ran exactly three times.
  • Configuration. ATTEMPTS=2 WAIT=1 run ... sets the two variables only for this one command. The recorded sleep calls, 1 and 1, prove that the script used the configured wait time. $'1\n1' is a string with a newline between the two values (lesson 47).

Running the Tests

All eight tests pass, and the whole run takes well under a second because nothing waits and nothing goes over the network. As in lesson 185, Bats itself could not be installed where this lesson was prepared, which had no network access; the tests were executed with a stand-in harness that implements the Bats features used here, plus load, and prints TAP output in the format of bats --tap:

$ bats --tap test/check-site.bats
1..8
ok 1 a healthy site is reported once, without waiting or restarting
ok 2 curl is called with fail, timeout and the URL
ok 3 a short outage is retried after waiting
ok 4 a site that stays down is restarted and checked again
ok 5 a site still down after the restart exits with status 1
ok 6 a failed restart exits with status 1 and skips the final check
ok 7 ATTEMPTS and WAIT can be changed through the environment
ok 8 a missing argument is a usage error

To confirm that the tests really guard the behavior, a plausible bug was introduced: the condition (( i < ATTEMPTS )) && was removed, so the script also waits after its last failed attempt, which delays every restart for no reason. Two tests detect it through the recorded sleep calls, although every message the script prints is still correct:

not ok 4 a site that stays down is restarted and checked again
# (in test file test/check-site.bats, line 47)
#   `[ "$(mock_calls sleep | wc -l)" -eq 3 ]' failed
...
not ok 7 ATTEMPTS and WAIT can be changed through the environment
# (in test file test/check-site.bats, line 68)
#   `[ "$(mock_calls sleep)" = '1
1' ]' failed

Deciding What to Mock

Mocks make tests fast and safe, but every mock is an assumption about how the real command behaves. If the assumption is wrong, the tests pass and the script still fails in production. A few guidelines keep that risk small:

  • Mock at the boundary. Replace the commands that reach outside the test: the network (curl, ssh), the system (sudo, systemctl, apt-get), time (sleep, date) and anything destructive. Let simple local tools such as grep, sed and sort run for real; they are fast and deterministic, and faking them only adds assumptions.
  • Base fake behavior on real behavior. Use real exit codes, like curl's 7 and 22, and real output formats, copied from an actual run. A fake that returns statuses the real program never uses tests a situation that cannot happen.
  • Prefer checking results over checking every call. Checking that the right service was restarted is valuable; checking the exact order of every option makes tests break whenever the script is reformatted. Check arguments when they carry meaning, as --fail and --max-time do here.
  • Keep some tests against the real commands. A few integration tests in a disposable environment, such as a Docker container with a real web server and service (lessons 175 and 176), confirm that the assumptions built into the fakes still hold. Fast mocked tests run on every change; slower real tests run less often.

The next lesson looks at testing error paths and exit codes in more depth; fakes like the ones in this lesson are often the easiest way to provoke the failures those tests need.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Mocking Commands During Script Tests and get answers drawn from it.

Signed-in readers only.