In this lesson, you will learn how to safely test your scripts by replacing real system commands with "mocks" that simulate expected behavior without affecting your actual environment.
Why Mock?
When writing robust Bash scripts, you often rely on external tools like curl, apt, or systemctl. However, running these in a test environment is dangerous—you don't want to actually install software or restart services just to see if your script handles an error correctly. Mocking involves creating a fake version of a command that intercepts the call, returns a pre-defined result, and allows your script to continue as if the real tool was executed.
The Strategy: PATH Manipulation
The most effective way to mock a command in Bash is to take advantage of how the shell locates programs. When you type a command, Bash searches for the executable in the directories listed in your $PATH variable. You can create a temporary directory, place a "fake" script inside it, and prepend that directory to your $PATH.
A Practical Example
Imagine your script relies on a command called check_status. Instead of running the real, complex tool, create a mock during your test suite:
# 1. Create a directory for mocks
mkdir -p ./mock_bin
# 2. Create the fake command
echo -e '#!/bin/bash\necho "MOCK_SUCCESS"' > ./mock_bin/check_status
chmod +x ./mock_bin/check_status
# 3. Inject the mock into the PATH for your test
export PATH="$(pwd)/mock_bin:$PATH"
# 4. Run your script
./my_script.sh
When my_script.sh calls check_status, the shell finds your version in ./mock_bin first and runs it, ignoring the real system tool entirely. This allows you to write test cases for scenarios that are usually hard to trigger, such as forcing a fake command to return a specific exit code (e.g., exit 1) to ensure your script’s error-handling logic actually works. By isolating these dependencies, you gain full control over the execution environment, making your unit tests predictable and lightning-fast.
Key Takeaway: By prepending a directory of fake executables to your PATH, you can simulate any system response, ensuring your script logic is tested against controlled outcomes rather than unpredictable real-world side effects.