Skip to content
Kate Ward edited this page Sep 24, 2017 · 11 revisions

Cookbook

Asserts

Using command output in assert message.

Let's say a function was called, and the output should be included to help in debugging the test. This is the recommended way to do so.

test_good_bad.sh

#!/bin/bash
  
good() { echo "Wohoo!!"; }
bad() { echo "Booo :-("; return 123; }

test_functions() {
  # Naively hope that all functions return true.
  while read desc fn; do
    output=$(${fn} 2>&1); rtrn=$?
    assertTrue "${desc}: unexpected error (${rtrn}); ${output}" ${rtrn}
  done <<EOF
good() good
bad()  bad
EOF
}

. ~/lib/sh/shunit2

Testing the code show that the bad output is added to the assertTrue output.

$ ./test_good_bad.sh 
test_functions
ASSERT:bad(): unexpected error (123); Booo :-(

Ran 1 test.

FAILED (failures=1)

Misc

Passing arguments to test script.

Passing command-line arguments to a test script is not a problem, as long as one small requirement is met. Before calling shunit2, use shift to shift all the command-line arguments off the stack.

test_date_cmd.sh -- The following code demonstrates proper usage.

#!/bin/bash
  
# Echo any provided arguments.
[ $# -gt 0 ] && echo "ARGC: $# 1:$1 2:$2 3:$3"

test_date_cmd() {
  ( date '+%a' >/dev/null 2>&1 )
  local rtrn=$?
  assertTrue "unexpected date error; ${rtrn}" ${rtrn}
}

# Eat all command-line arguments before calling shunit2.
shift $#
. ~/lib/sh/shunit2

Calling the command without arguments.

$ ./test_date_cmd.sh 
test_date_cmd

Ran 1 test.

OK

Calling the command with arguments.

#:3 1:a 2:b 3:c
test_date_cmd

Ran 1 test.

OK
Clone this wiki locally