 rogervinas
       / 
        tests-everywhere
      
        rogervinas
       / 
        tests-everywhere
      
    
    🤠 Tests, Tests Everywhere!
Bash testing this simple Hello World with BATS
Show me the code
Implementation
- Create helloMessagefunction in hello-message.bash:
function helloMessage() {
  echo "Hello World!"
}
- Create helloConsolefunction in hello-console.bash:
function helloConsole() {
  local text=$1
  echo "$text"
}
- Create helloAppfunction in hello-app.bash:
function helloApp() {
  local messageFn=$1
  local consoleFn=$2
  $consoleFn "$($messageFn)"
}
Note that helloApp function receives the two other functions as parameters and just executes them.
- Create a main script hello.bash that just loads the 3 required scripts and executes helloApppassinghelloMessageandhelloConsolefunctions as parameters:
source "$(dirname "${BASH_SOURCE[0]}")/hello-message.bash"
source "$(dirname "${BASH_SOURCE[0]}")/hello-console.bash"
source "$(dirname "${BASH_SOURCE[0]}")/hello-app.bash"
helloApp helloMessage helloConsole
Test
Following BATS Tutorial > Your first test ...
- For simplicity create all tests in hello.bats file 
- Configure current directory and load some helper modules in - setupfunction:
 
setup() {
  load 'test_helper/bats-support/load'
  load 'test_helper/bats-assert/load'
  DIR="$( cd "$( dirname "$BATS_TEST_FILENAME" )" >/dev/null 2>&1 && pwd )"
  PATH="$DIR/../src:$PATH"
}
- Test helloMessagefunction using assert_output helper:
@test "helloMessage should return hello world" {
  source hello-message.bash
  run helloMessage
  assert_output "Hello World!"
}
- Test helloAppfunction:
@test "helloApp should print hello message" {
  # 4.1 Create a helloMessage function mock
  # that will return "Hello Test!"
  function helloMessageMock() {
    echo "Hello Test!"
  }
  # 4.2 Create a helloConsole function mock
  # that will print parameter passed within "helloConsoleMock[...]"
  function helloConsoleMock() {
    local text=$1
    echo "helloConsoleMock[$text]"
  }
  # 4.3 Load helloApp function, the one we want to test
  source hello-app.bash
  # 4.4 Execute helloApp passing mock functions
  run helloApp helloMessageMock helloConsoleMock
  # 4.5 Assert helloConsoleMock has been called once
  # with the returned message by helloMessageMock
  assert_output "helloConsoleMock[Hello Test!]"
}
- Test the whole hello.bashscript too:
@test "hello.bash should print hello world" {
  run hello.bash
  assert_output "Hello World!"
}
- Test output should look like:
hello.bats
 ✓ helloMessage should return hello world
 ✓ helloApp should print hello message
 ✓ hello.bash should print hello world
3 tests, 0 failures
Take a look at the other Libraries and Add-ons that may be useful in the future. For example, there is a couple of bats-mock libraries that can be used to mock programs (but unfortunately not able to mock functions).
Happy Testing! 💙
 
 
              
 
    
Top comments (0)