1

I am using shUnit2 to do unit testing in Bash shell scripts.

I have code like this:

if [ ! -x /usr/local/rvm/bin/rvm ]; then
  ...
fi

etc

I want to write unit tests to test this code, but to do that I need to stub out the behaviour of Bash file tests.

One way I could do this would be to refactor as:

if ! test -x /usr/local/rvm/bin/rvm; then
  ...
fi

Then I can stub out the test built-in using something like:

test() {
  case "$*" in
  "-x /usr/local/rvm/bin/rvm")
    false
    ;;
  esac
}

Creating the files that are expected during setUp might be an option sometimes, but obviously not always.

Or, I could refactor to move file tests inside custom functions, e.g.

rvm_installed() {
  [ -x /usr/local/rvm/bin/rvm ]
}

Then I can stub this function in my tests.

Is there any way to test this code without refactoring it though?

Alex Harvey
  • 14,494
  • 5
  • 61
  • 97

2 Answers2

2

You can stub [ just as you can stub test:

[() {
  case "$*" in
  "-x /usr/local/rvm/bin/rvm")
    false
    ;;
  esac
}
janos
  • 120,954
  • 29
  • 226
  • 236
0

What @janos said is correct, but it breaks shUnit2 if something like [ is stubbed.

I raised a pull request that was merged to fix this problem in the way @janos suggested in the comments. This fix will hopefully be released eventually in shUnit2 2.1.7.

In the mean time the options are:

1) Use the patched version above.

2) See also suggestions about how to use a wrapper file in this example here: https://github.com/zofrex/bourne-shell-unit-testing

Alex Harvey
  • 14,494
  • 5
  • 61
  • 97