kward / shunit2

shUnit2 is a xUnit based unit test framework for Bourne based shell scripts.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use assertNull correctly?

richelbilderbeek opened this issue · comments

I expected assertNull to need only one argument. AFAICS, it needs two. I hope my misconception can be fixed.

I have seen the assert tests to try to find out how assertNull is used. I've found:

testAssertNull()
{
  ( assertNull '' >"${stdoutF}" 2>"${stderrF}" )
  # Others...
}

It appears assertNull needs two arguments (three if a message is added)? I expected assertNull only needs one argument: the expression to be tested to be null. So if I write a function, create_null that returns nothing, this should be detected by assertNull. Here a minimal script that does so:

#!/bin/bash

function create_null()
{
  echo ""
}

test_create_null()
{
  assertNull `create_null`
}

# load shunit2
. ../../shunit2/source/2.1/src/shunit2

Output is:

test_create_null
shunit2:ERROR assertNull() requires one or two arguments; 0 given

Ran 1 test.

OK

I have tried multiple ways, but cannot get assertNull to work on one, two or three arguments. What do I overlook? What is my misconception?

Thanks, Richel

This is a corrected version of your test_create_null() function. Note the '"' chars that were added.

test_create_null()
{
  assertNull "`create_null`"
}

The reason the " characters are needed in this case is that the output of create_null() is an empty string. The shell optimizes that empty string away because create_null was called inside a sub-shell (inside the backtick '`' chars), and that sub-shell actually ate the empty output. Back in the main shell, because there was no resulting output, nothing is passed to assertNull(), causing the sanity checks in assertNull() to fail. Wrapping the create_null() call in " chars though forcefully wraps that empty output into a string value, and that empty string value is then passed to assertNull(), enabling things to work.

I hope this helps!