In this lesson, you will learn how to create and leverage isolated, realistic mock environments to verify that your Bash scripts behave correctly when interacting with complex system dependencies.
Beyond Unit Tests
While unit testing checks if an individual function works, Integration Testing verifies that your script correctly interacts with the "real world"—like filesystems, network sockets, or databases. Running these tests directly on your host machine is dangerous because you might accidentally delete system files or clutter your databases with test data.
To test safely, we create a "mock environment." This is a sandboxed space that mimics the production environment’s structure without the risk of collateral damage.
Building a Realistic Mock
The most effective way to do this in Linux is by combining Container Runtime Orchestration with local filesystem staging. By spinning up a short-lived container that mirrors your production OS, you ensure your script encounters the same environment variables, users, and installed packages it will see in production.
Consider this pattern for a test script:
# 1. Spin up a clean container instance
CONTAINER_ID=$(docker run -d my-app-mock-image sleep 300)
# 2. Inject your script into the mock environment
docker cp my_script.sh "$CONTAINER_ID":/usr/local/bin/my_script.sh
# 3. Execute the script within the mock context
docker exec "$CONTAINER_ID" /usr/local/bin/my_script.sh
# 4. Verify the side effects (e.g., check if a file was created)
docker exec "$CONTAINER_ID" test -f /var/log/my_app/output.log
EXIT_CODE=$?
# 5. Clean up the environment
docker rm -f "$CONTAINER_ID"
Why this works
By using docker cp and docker exec, you force your script to deal with reality—such as missing directories, restricted permissions, or network latency—without affecting your actual host system. If your script relies on systemd timers or specific mount point management configurations, you can bake those into your mock image beforehand.
This approach ensures that if a script passes in the container, it will almost certainly succeed in production. If it fails, you have a perfectly reproducible "crime scene" to debug without breaking your own workstation.
Key Takeaway: Integration testing environments allow you to safely simulate production-grade system interactions inside isolated, disposable containers to catch environmental bugs before they reach your users.